Files

Return to Package Diff Home.
Brought to you by Intrinsic.

Package Diff: typescript @ 3.3.4000 .. 3.4.5

lib/lib.dom.d.ts

@@ -203,6 +203,10 @@
type?: ClientTypes;
}
+interface ClipboardEventInit extends EventInit {
+ clipboardData?: DataTransfer | null;
+}
+
interface CloseEventInit extends EventInit {
code?: number;
reason?: string;
@@ -448,6 +452,10 @@
shiftKey?: boolean;
}
+interface EventSourceInit {
+ withCredentials?: boolean;
+}
+
interface ExceptionInformation {
domain?: string | null;
}
@@ -479,12 +487,16 @@
preventScroll?: boolean;
}
+interface FullscreenOptions {
+ navigationUI?: FullscreenNavigationUI;
+}
+
interface GainOptions extends AudioNodeOptions {
gain?: number;
}
interface GamepadEventInit extends EventInit {
- gamepad?: Gamepad;
+ gamepad: Gamepad;
}
interface GetNotificationOptions {
@@ -619,15 +631,17 @@
}
interface MediaKeyMessageEventInit extends EventInit {
- message?: ArrayBuffer | null;
- messageType?: MediaKeyMessageType;
+ message: ArrayBuffer;
+ messageType: MediaKeyMessageType;
}
interface MediaKeySystemConfiguration {
audioCapabilities?: MediaKeySystemMediaCapability[];
distinctiveIdentifier?: MediaKeysRequirement;
initDataTypes?: string[];
+ label?: string;
persistentState?: MediaKeysRequirement;
+ sessionTypes?: string[];
videoCapabilities?: MediaKeySystemMediaCapability[];
}
@@ -744,6 +758,8 @@
buttons?: number;
clientX?: number;
clientY?: number;
+ movementX?: number;
+ movementY?: number;
relatedTarget?: EventTarget | null;
screenX?: number;
screenY?: number;
@@ -1462,6 +1478,11 @@
source?: ServiceWorker | MessagePort | null;
}
+interface ShadowRootInit {
+ delegatesFocus?: boolean;
+ mode: ShadowRootMode;
+}
+
interface StereoPannerOptions extends AudioNodeOptions {
pan?: number;
}
@@ -1629,6 +1650,7 @@
(evt: Event): void;
}
+/** The ANGLE_instanced_arrays extension is part of the WebGL API and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type. */
interface ANGLE_instanced_arrays {
drawArraysInstancedANGLE(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei): void;
drawElementsInstancedANGLE(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, primcount: GLsizei): void;
@@ -1636,6 +1658,7 @@
readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: GLenum;
}
+/** The AbortController interface represents a controller object that allows you to abort one or more DOM requests as and when desired. */
interface AbortController {
/**
* Returns the AbortSignal object associated with this object.
@@ -1654,16 +1677,17 @@
};
interface AbortSignalEventMap {
- "abort": ProgressEvent;
+ "abort": Event;
}
+/** The AbortSignal interface represents a signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */
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;
+ onabort: ((this: AbortSignal, ev: Event) => any) | null;
addEventListener<K extends keyof AbortSignalEventMap>(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
removeEventListener<K extends keyof AbortSignalEventMap>(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
@@ -1708,6 +1732,7 @@
length: number;
}
+/** The AnalyserNode interface represents a node able to provide real-time frequency and time-domain analysis information. It is an AudioNode that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations. */
interface AnalyserNode extends AudioNode {
fftSize: number;
readonly frequencyBinCount: number;
@@ -1776,6 +1801,7 @@
new(): AnimationEffect;
};
+/** The AnimationEvent interface represents events providing information related to animations. */
interface AnimationEvent extends Event {
readonly animationName: string;
readonly elapsedTime: number;
@@ -1865,6 +1891,7 @@
readonly UPDATEREADY: number;
};
+/** This type represents a DOM element's attribute as an object. In most DOM methods, you will probably directly retrieve the attribute as a string (e.g., Element.getAttribute(), but certain functions (e.g., Element.getAttributeNode()) or means of iterating give Attr types. */
interface Attr extends Node {
readonly localName: string;
readonly name: string;
@@ -1880,6 +1907,7 @@
new(): Attr;
};
+/** Objects of these types are designed to hold small audio snippets, typically less than 45 s. For longer sounds, objects implementing the MediaElementAudioSourceNode are more suitable. The buffer contains data in the following format:  non-interleaved IEEE754 32-bit linear PCM with a nominal range between -1 and +1, that is, 32bits floating point buffer, with each samples between -1.0 and 1.0. If the AudioBuffer has multiple channels, they are stored in separate buffer. */
interface AudioBuffer {
readonly duration: number;
readonly length: number;
@@ -1895,6 +1923,7 @@
new(options: AudioBufferOptions): AudioBuffer;
};
+/** The AudioBufferSourceNode interface is an AudioScheduledSourceNode which represents an audio source consisting of in-memory audio data, stored in an AudioBuffer. It's especially useful for playing back audio which has particularly stringent timing accuracy requirements, such as for sounds that must match a specific rhythm and can be kept in memory rather than being played from disk or the network. */
interface AudioBufferSourceNode extends AudioScheduledSourceNode {
buffer: AudioBuffer | null;
readonly detune: AudioParam;
@@ -1914,6 +1943,7 @@
new(context: BaseAudioContext, options?: AudioBufferSourceOptions): AudioBufferSourceNode;
};
+/** The AudioContext interface represents an audio-processing graph built from audio modules linked together, each represented by an AudioNode. */
interface AudioContext extends BaseAudioContext {
readonly baseLatency: number;
readonly outputLatency: number;
@@ -1935,6 +1965,7 @@
new(contextOptions?: AudioContextOptions): AudioContext;
};
+/** AudioDestinationNode has no output (as it is the output, no more AudioNode can be linked after it in the audio graph) and one input. The number of channels in the input must be between 0 and the maxChannelCount value or an exception is raised. */
interface AudioDestinationNode extends AudioNode {
readonly maxChannelCount: number;
}
@@ -1944,6 +1975,7 @@
new(): AudioDestinationNode;
};
+/** The AudioListener interface represents the position and orientation of the unique person listening to the audio scene, and is used in audio spatialization. All PannerNodes spatialize in relation to the AudioListener stored in the BaseAudioContext.listener attribute. */
interface AudioListener {
readonly forwardX: AudioParam;
readonly forwardY: AudioParam;
@@ -1965,6 +1997,7 @@
new(): AudioListener;
};
+/** The AudioNode interface is a generic interface for representing an audio processing module. Examples include: */
interface AudioNode extends EventTarget {
channelCount: number;
channelCountMode: ChannelCountMode;
@@ -1988,6 +2021,7 @@
new(): AudioNode;
};
+/** The Web Audio API's AudioParam interface represents an audio-related parameter, usually a parameter of an AudioNode (such as GainNode.gain). */
interface AudioParam {
automationRate: AutomationRate;
readonly defaultValue: number;
@@ -2017,6 +2051,7 @@
new(): AudioParamMap;
};
+/** The Web Audio API AudioProcessingEvent represents events that occur when a ScriptProcessorNode input buffer is ready to be processed. */
interface AudioProcessingEvent extends Event {
readonly inputBuffer: AudioBuffer;
readonly outputBuffer: AudioBuffer;
@@ -2047,13 +2082,14 @@
new(): AudioScheduledSourceNode;
};
+/** The AudioTrack interface represents a single audio track from one of the HTML media elements, <audio> or <video>. */
interface AudioTrack {
enabled: boolean;
readonly id: string;
kind: string;
readonly label: string;
language: string;
- readonly sourceBuffer: SourceBuffer;
+ readonly sourceBuffer: SourceBuffer | null;
}
declare var AudioTrack: {
@@ -2067,6 +2103,7 @@
"removetrack": TrackEvent;
}
+/** The AudioTrackList interface is used to represent a list of the audio tracks contained within a given HTML media element, with each track represented by a separate AudioTrack object in the list. */
interface AudioTrackList extends EventTarget {
readonly length: number;
onaddtrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null;
@@ -2165,6 +2202,7 @@
new(): BaseAudioContext;
};
+/** The beforeunload event is fired when the window, the document and its resources are about to be unloaded. */
interface BeforeUnloadEvent extends Event {
returnValue: any;
}
@@ -2196,6 +2234,7 @@
new(): BhxBrowser;
};
+/** The BiquadFilterNode interface represents a simple low-order filter, and is created using the AudioContext.createBiquadFilter() method. It is an AudioNode that can represent different kinds of filters, tone control devices, and graphic equalizers. */
interface BiquadFilterNode extends AudioNode {
readonly Q: AudioParam;
readonly detune: AudioParam;
@@ -2210,6 +2249,7 @@
new(context: BaseAudioContext, options?: BiquadFilterOptions): BiquadFilterNode;
};
+/** A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. */
interface Blob {
readonly size: number;
readonly type: string;
@@ -2267,6 +2307,7 @@
messageerror: MessageEvent;
}
+/** The ByteLengthQueuingStrategy interface of the the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. */
interface ByteLengthQueuingStrategy extends QueuingStrategy<ArrayBufferView> {
highWaterMark: number;
size(chunk: ArrayBufferView): number;
@@ -2277,6 +2318,7 @@
new(options: { highWaterMark: number }): ByteLengthQueuingStrategy;
};
+/** The CDATASection interface represents a CDATA section that can be used within XML to include extended portions of unescaped text. The symbols < and & don’t need escaping as they normally do when inside a CDATA section. */
interface CDATASection extends Text {
}
@@ -2285,12 +2327,14 @@
new(): CDATASection;
};
+/** The CSS interface holds useful CSS-related methods. No object with this interface are implemented: it contains only static methods and therefore is a utilitarian interface. */
interface CSS {
escape(value: string): string;
supports(property: string, value?: string): boolean;
}
declare var CSS: CSS;
+/** An object implementing the CSSConditionRule interface represents a single condition CSS at-rule, which consists of a condition and a statement block. It is a child of CSSGroupingRule. */
interface CSSConditionRule extends CSSGroupingRule {
conditionText: string;
}
@@ -2309,6 +2353,7 @@
new(): CSSFontFaceRule;
};
+/** An object implementing the CSSGroupingRule interface represents any CSS at-rule that contains other rules nested within it. */
interface CSSGroupingRule extends CSSRule {
readonly cssRules: CSSRuleList;
deleteRule(index: number): void;
@@ -2331,6 +2376,7 @@
new(): CSSImportRule;
};
+/** The CSSKeyframeRule interface describes an object representing a set of style for a given keyframe. It corresponds to the contains of a single keyframe of a @keyframes at-rule. It implements the CSSRule interface with a type value of 8 (CSSRule.KEYFRAME_RULE). */
interface CSSKeyframeRule extends CSSRule {
keyText: string;
readonly style: CSSStyleDeclaration;
@@ -2341,6 +2387,7 @@
new(): CSSKeyframeRule;
};
+/** The CSSKeyframesRule interface describes an object representing a complete set of keyframes for a CSS animation. It corresponds to the contains of a whole @keyframes at-rule. It implements the CSSRule interface with a type value of 7 (CSSRule.KEYFRAMES_RULE). */
interface CSSKeyframesRule extends CSSRule {
readonly cssRules: CSSRuleList;
name: string;
@@ -2354,6 +2401,7 @@
new(): CSSKeyframesRule;
};
+/** The CSSMediaRule is an interface representing a single CSS @media rule. It implements the CSSConditionRule interface, and therefore the CSSGroupingRule and the CSSRule interface with a type value of 4 (CSSRule.MEDIA_RULE). */
interface CSSMediaRule extends CSSConditionRule {
readonly media: MediaList;
}
@@ -2363,6 +2411,7 @@
new(): CSSMediaRule;
};
+/** The CSSNamespaceRule interface describes an object representing a single CSS @namespace at-rule. It implements the CSSRule interface, with a type value of 10 (CSSRule.NAMESPACE_RULE). */
interface CSSNamespaceRule extends CSSRule {
readonly namespaceURI: string;
readonly prefix: string;
@@ -2373,6 +2422,7 @@
new(): CSSNamespaceRule;
};
+/** CSSPageRule is an interface representing a single CSS @page rule. It implements the CSSRule interface with a type value of 6 (CSSRule.PAGE_RULE). */
interface CSSPageRule extends CSSRule {
readonly pseudoClass: string;
readonly selector: string;
@@ -2385,6 +2435,7 @@
new(): CSSPageRule;
};
+/** The CSSRule interface represents a single CSS rule. There are several types of rules, listed in the Type constants section below. */
interface CSSRule {
cssText: string;
readonly parentRule: CSSRule | null;
@@ -2421,6 +2472,7 @@
readonly VIEWPORT_RULE: number;
};
+/** A CSSRuleList is an (indirect-modify only) array-like object containing an ordered collection of CSSRule objects. */
interface CSSRuleList {
readonly length: number;
item(index: number): CSSRule | null;
@@ -2432,6 +2484,7 @@
new(): CSSRuleList;
};
+/** The CSSStyleDeclaration API represents an object that is a CSS declaration block, that exposes style information and various style-related methods and properties. */
interface CSSStyleDeclaration {
alignContent: string | null;
alignItems: string | null;
@@ -2903,6 +2956,7 @@
new(): CSSStyleDeclaration;
};
+/** CSSStyleRule represents a single CSS style rule. It implements the CSSRule interface with a type value of 1 (CSSRule.STYLE_RULE). */
interface CSSStyleRule extends CSSRule {
selectorText: string;
readonly style: CSSStyleDeclaration;
@@ -2913,6 +2967,7 @@
new(): CSSStyleRule;
};
+/** The CSSStyleSheet interface represents a single CSS style sheet. It inherits properties and methods from its parent, StyleSheet. */
interface CSSStyleSheet extends StyleSheet {
readonly cssRules: CSSRuleList;
/** @deprecated */
@@ -2950,6 +3005,7 @@
new(): CSSStyleSheet;
};
+/** The CSSSupportsRule interface describes an object representing a single CSS @supports at-rule. It implements the CSSConditionRule interface, and therefore the CSSRule and CSSGroupingRule interfaces with a type value of 12 (CSSRule.SUPPORTS_RULE). */
interface CSSSupportsRule extends CSSConditionRule {
}
@@ -2958,6 +3014,7 @@
new(): CSSSupportsRule;
};
+/** The Cache interface provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the ServiceWorker life cycle. Note that the Cache interface is exposed to windowed scopes as well as workers. You don't have to use it in conjunction with service workers, even though it is defined in the service worker spec. */
interface Cache {
add(request: RequestInfo): Promise<void>;
addAll(requests: RequestInfo[]): Promise<void>;
@@ -2973,6 +3030,7 @@
new(): Cache;
};
+/** The CacheStorage interface represents the storage for Cache objects. */
interface CacheStorage {
delete(cacheName: string): Promise<boolean>;
has(cacheName: string): Promise<boolean>;
@@ -3023,6 +3081,7 @@
filter: string;
}
+/** The CanvasGradient interface represents an opaque object describing a gradient. It is returned by the methods CanvasRenderingContext2D.createLinearGradient() or CanvasRenderingContext2D.createRadialGradient(). */
interface CanvasGradient {
/**
* Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset
@@ -3074,6 +3133,7 @@
setLineDash(segments: number[]): void;
}
+/** The CanvasPattern interface represents an opaque object describing a pattern, based on an image, a canvas, or a video, created by the CanvasRenderingContext2D.createPattern() method. */
interface CanvasPattern {
/**
* Sets the transformation matrix that will be used when rendering the pattern during a fill or
@@ -3093,6 +3153,7 @@
strokeRect(x: number, y: number, w: number, h: number): void;
}
+/** The CanvasRenderingContext2D interface, part of the Canvas API, provides the 2D rendering context for the drawing surface of a <canvas> element. It is used for drawing shapes, text, images, and other objects. */
interface CanvasRenderingContext2D extends CanvasState, CanvasTransform, CanvasCompositing, CanvasImageSmoothing, CanvasFillStrokeStyles, CanvasShadowStyles, CanvasFilters, CanvasRect, CanvasDrawPath, CanvasUserInterface, CanvasText, CanvasDrawImage, CanvasImageData, CanvasPathDrawingStyles, CanvasTextDrawingStyles, CanvasPath {
readonly canvas: HTMLCanvasElement;
}
@@ -3156,6 +3217,7 @@
new(): CaretPosition;
};
+/** The ChannelMergerNode interface, often used in conjunction with its opposite, ChannelSplitterNode, reunites different mono inputs into a single output. Each input is used to fill a channel of the output. This is useful for accessing each channels separately, e.g. for performing channel mixing where gain must be separately controlled on each channel. */
interface ChannelMergerNode extends AudioNode {
}
@@ -3164,6 +3226,7 @@
new(context: BaseAudioContext, options?: ChannelMergerOptions): ChannelMergerNode;
};
+/** The ChannelSplitterNode interface, often used in conjunction with its opposite, ChannelMergerNode, separates the different channels of an audio source into a set of mono outputs. This is useful for accessing each channel separately, e.g. for performing channel mixing where gain must be separately controlled on each channel. */
interface ChannelSplitterNode extends AudioNode {
}
@@ -3172,6 +3235,7 @@
new(context: BaseAudioContext, options?: ChannelSplitterOptions): ChannelSplitterNode;
};
+/** The CharacterData abstract interface represents a Node object that contains characters. This is an abstract interface, meaning there aren't any object of type CharacterData: it is implemented by other interfaces, like Text, Comment, or ProcessingInstruction which aren't abstract. */
interface CharacterData extends Node, NonDocumentTypeChildNode, ChildNode {
data: string;
readonly length: number;
@@ -3237,8 +3301,19 @@
new(): ClientRectList;
};
+interface Clipboard extends EventTarget {
+ readText(): Promise<string>;
+ writeText(data: string): Promise<void>;
+}
+
+declare var Clipboard: {
+ prototype: Clipboard;
+ new(): Clipboard;
+};
+
+/** The ClipboardEvent interface represents events providing information related to modification of the clipboard, that is cut, copy, and paste events. */
interface ClipboardEvent extends Event {
- readonly clipboardData: DataTransfer;
+ readonly clipboardData: DataTransfer | null;
}
declare var ClipboardEvent: {
@@ -3246,11 +3321,7 @@
new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent;
};
-interface ClipboardEventInit extends EventInit {
- data?: string;
- dataType?: string;
-}
-
+/** A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute. */
interface CloseEvent extends Event {
readonly code: number;
readonly reason: string;
@@ -3264,6 +3335,7 @@
new(type: string, eventInitDict?: CloseEventInit): CloseEvent;
};
+/** The Comment interface represents textual notations within markup; although it is generally not visually shown, such comments are available to be read in the source view. Comments are represented in HTML and XML as content between '<!--' and '-->'. In XML, the character sequence '--' cannot be used within a comment. */
interface Comment extends CharacterData {
}
@@ -3272,6 +3344,7 @@
new(data?: string): Comment;
};
+/** The DOM CompositionEvent represents events that occur due to the user indirectly entering text. */
interface CompositionEvent extends UIEvent {
readonly data: string;
readonly locale: string;
@@ -3292,6 +3365,7 @@
publicInfo?: Uint8Array;
}
+/** The Console object provides access to the browser's debugging console (e.g. the Web Console in Firefox). The specifics of how it works varies from browser to browser, but there is a de facto set of features that are typically provided. */
interface Console {
memory: any;
assert(condition?: boolean, message?: string, ...data: any[]): void;
@@ -3338,6 +3412,7 @@
new(context: BaseAudioContext, options?: ConstantSourceOptions): ConstantSourceNode;
};
+/** The ConvolverNode interface is an AudioNode that performs a Linear Convolution on a given AudioBuffer, often used to achieve a reverb effect. A ConvolverNode always has exactly one input and one output. */
interface ConvolverNode extends AudioNode {
buffer: AudioBuffer | null;
normalize: boolean;
@@ -3348,6 +3423,7 @@
new(context: BaseAudioContext, options?: ConvolverOptions): ConvolverNode;
};
+/** The Coordinates interface represents the position and altitude of the device on Earth, as well as the accuracy with which these properties are calculated. */
interface Coordinates {
readonly accuracy: number;
readonly altitude: number | null;
@@ -3358,6 +3434,7 @@
readonly speed: number | null;
}
+/** The CountQueuingStrategy interface of the the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. */
interface CountQueuingStrategy extends QueuingStrategy {
highWaterMark: number;
size(chunk: any): 1;
@@ -3368,6 +3445,7 @@
new(options: { highWaterMark: number }): CountQueuingStrategy;
};
+/** The Crypto interface represents basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives. */
interface Crypto {
readonly subtle: SubtleCrypto;
getRandomValues<T extends Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null>(array: T): T;
@@ -3378,6 +3456,7 @@
new(): Crypto;
};
+/** The CryptoKey interface represents a cryptographic key derived from a specific key algorithm. */
interface CryptoKey {
readonly algorithm: KeyAlgorithm;
readonly extractable: boolean;
@@ -3426,6 +3505,7 @@
new<T>(typeArg: string, eventInitDict?: CustomEventInit<T>): CustomEvent<T>;
};
+/** The DOMError interface describes an error object that contains an error name. */
interface DOMError {
readonly name: string;
toString(): string;
@@ -3436,6 +3516,7 @@
new(): DOMError;
};
+/** The DOMException interface represents an abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. */
interface DOMException {
readonly code: number;
readonly message: string;
@@ -3497,6 +3578,7 @@
readonly WRONG_DOCUMENT_ERR: number;
};
+/** The DOMImplementation interface represent an object providing methods which are not dependent on any particular document. Such an object is returned by the Document.implementation property. */
interface DOMImplementation {
createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document;
createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType;
@@ -3599,6 +3681,8 @@
rotateFromVector(x?: number, y?: number): DOMMatrix;
scale(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;
scale3d(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;
+ /** @deprecated */
+ scaleNonUniform(scaleX?: number, scaleY?: number): DOMMatrix;
skewX(sx?: number): DOMMatrix;
skewY(sy?: number): DOMMatrix;
toFloat32Array(): Float32Array;
@@ -3616,6 +3700,7 @@
fromMatrix(other?: DOMMatrixInit): DOMMatrixReadOnly;
};
+/** The DOMParser interface provides the ability to parse XML or HTML source code from a string into a DOM Document. */
interface DOMParser {
parseFromString(str: string, type: SupportedType): Document;
}
@@ -3726,6 +3811,7 @@
new(): DOMSettableTokenList;
};
+/** A type returned by some APIs which contains a list of DOMString (strings). */
interface DOMStringList {
/**
* Returns the number of strings in strings.
@@ -3748,6 +3834,7 @@
new(): DOMStringList;
};
+/** Used by the dataset HTML attribute to represent data for custom attributes added to elements. */
interface DOMStringMap {
[name: string]: string | undefined;
}
@@ -3757,6 +3844,7 @@
new(): DOMStringMap;
};
+/** The DOMTokenList interface represents a set of space-separated tokens. Such a set is returned by Element.classList, HTMLLinkElement.relList, HTMLAnchorElement.relList, HTMLAreaElement.relList, HTMLIframeElement.sandbox, or HTMLOutputElement.htmlFor. It is indexed beginning with 0 as with JavaScript Array objects. DOMTokenList is always case-sensitive. */
interface DOMTokenList {
/**
* Returns the number of tokens.
@@ -3829,6 +3917,7 @@
new(): DataCue;
};
+/** The DataTransfer object is used to hold the data that is being dragged during a drag and drop operation. It may hold one or more data items, each of one or more data types. For more information about drag and drop, see HTML Drag and Drop API. */
interface DataTransfer {
dropEffect: string;
effectAllowed: string;
@@ -3869,6 +3958,7 @@
new(): DataTransfer;
};
+/** The DataTransferItem object represents one drag data item. During a drag operation, each drag event has a dataTransfer property which contains a list of drag data items. Each item in the list is a DataTransferItem object. */
interface DataTransferItem {
/**
* Returns the drag data item kind, one of: "string",
@@ -3896,6 +3986,7 @@
new(): DataTransferItem;
};
+/** The DataTransferItemList object is a list of DataTransferItem objects representing items being dragged. During a drag operation, each DragEvent has a dataTransfer property and that property is a DataTransferItemList. */
interface DataTransferItemList {
/**
* Returns the number of items in the drag data store.
@@ -3938,6 +4029,7 @@
new(): DeferredPermissionRequest;
};
+/** The DelayNode interface represents a delay-line; an AudioNode audio-processing module that causes a delay between the arrival of an input data and its propagation to the output. */
interface DelayNode extends AudioNode {
readonly delayTime: AudioParam;
}
@@ -3947,6 +4039,7 @@
new(context: BaseAudioContext, options?: DelayOptions): DelayNode;
};
+/** A DeviceAcceleration object provides information about the amount of acceleration the device is experiencing along all three axes. */
interface DeviceAcceleration {
readonly x: number | null;
readonly y: number | null;
@@ -3958,6 +4051,7 @@
new(): DeviceAcceleration;
};
+/** The DeviceLightEvent provides web developers with information from photo sensors or similiar detectors about ambient light levels near the device. For example this may be useful to adjust the screen's brightness based on the current ambient light level in order to save energy or provide better readability. */
interface DeviceLightEvent extends Event {
readonly value: number;
}
@@ -3967,6 +4061,7 @@
new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent;
};
+/** The DeviceMotionEvent provides web developers with information about the speed of changes for the device's position and orientation. */
interface DeviceMotionEvent extends Event {
readonly acceleration: DeviceAcceleration | null;
readonly accelerationIncludingGravity: DeviceAcceleration | null;
@@ -3980,6 +4075,7 @@
new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent;
};
+/** The DeviceOrientationEvent provides web developers with information from the physical orientation of the device running the web page. */
interface DeviceOrientationEvent extends Event {
readonly absolute: boolean;
readonly alpha: number | null;
@@ -3993,6 +4089,7 @@
new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent;
};
+/** A DeviceRotationRate object provides information about the rate at which the device is rotating around all three axes. */
interface DeviceRotationRate {
readonly alpha: number | null;
readonly beta: number | null;
@@ -4026,10 +4123,13 @@
interface DocumentEventMap extends GlobalEventHandlersEventMap, DocumentAndElementEventHandlersEventMap {
"fullscreenchange": Event;
"fullscreenerror": Event;
+ "pointerlockchange": Event;
+ "pointerlockerror": Event;
"readystatechange": ProgressEvent;
"visibilitychange": Event;
}
+/** The Document interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the DOM tree. */
interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, ParentNode, GlobalEventHandlers, DocumentAndElementEventHandlers {
/**
* Sets or gets the URL for the current document.
@@ -4186,6 +4286,8 @@
location: Location;
onfullscreenchange: ((this: Document, ev: Event) => any) | null;
onfullscreenerror: ((this: Document, ev: Event) => any) | null;
+ onpointerlockchange: ((this: Document, ev: Event) => any) | null;
+ onpointerlockerror: ((this: Document, ev: Event) => any) | null;
/**
* Fires when the state of the object has changed.
* @param ev The event
@@ -4283,68 +4385,11 @@
* When supplied, options's is can be used to create a customized built-in element.
*/
createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement;
+ createElementNS<K extends keyof SVGElementTagNameMap>(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: K): SVGElementTagNameMap[K];
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "cursor"): SVGCursorElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement;
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement;
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement;
- createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement;
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement;
- 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, options?: ElementCreationOptions): Element;
createElementNS(namespace: string | null, qualifiedName: string, options?: string | ElementCreationOptions): Element;
@@ -4483,6 +4528,7 @@
* resolves promise when done.
*/
exitFullscreen(): Promise<void>;
+ exitPointerLock(): void;
getAnimations(): Animation[];
/**
* Returns a reference to the first object with the specified value of the ID or NAME attribute.
@@ -4516,9 +4562,18 @@
getElementsByTagNameNS(namespaceURI: "http://www.w3.org/2000/svg", localName: string): HTMLCollectionOf<SVGElement>;
getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf<Element>;
/**
+ * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage.
+ */
+ getSelection(): Selection | null;
+ /**
* Gets a value indicating whether the object currently has focus.
*/
hasFocus(): boolean;
+ /**
+ * Returns a copy of node. If deep is true, the copy also includes the node's descendants.
+ * If node is a document or a shadow root, throws a
+ * "NotSupportedError" DOMException.
+ */
importNode<T extends Node>(importedNode: T, deep: boolean): T;
/**
* 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.
@@ -4565,9 +4620,6 @@
* @param content The text and HTML tags to write.
*/
writeln(...text: string[]): void;
- /**
- * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage.
- */
addEventListener<K extends keyof DocumentEventMap>(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
removeEventListener<K extends keyof DocumentEventMap>(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
@@ -4676,6 +4728,7 @@
createEvent(eventInterface: string): Event;
}
+/** The DocumentFragment interface represents a minimal document object that has no parent. It is used as a lightweight version of Document that stores a segment of a document structure comprised of nodes just like a standard document. The key difference is that because the document fragment isn't part of the active document tree structure, changes made to the fragment don't affect the document, cause reflow, or incur any performance impact that can occur when changes are made. */
interface DocumentFragment extends Node, NonElementParentNode, ParentNode {
getElementById(elementId: string): HTMLElement | null;
}
@@ -4687,6 +4740,8 @@
interface DocumentOrShadowRoot {
readonly activeElement: Element | null;
+ readonly fullscreenElement: Element | null;
+ readonly pointerLockElement: 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.
*/
@@ -4707,6 +4762,7 @@
new(options?: DocumentTimelineOptions): DocumentTimeline;
};
+/** The DocumentType interface represents a Node containing a doctype. */
interface DocumentType extends Node, ChildNode {
readonly name: string;
readonly publicId: string;
@@ -4718,6 +4774,7 @@
new(): DocumentType;
};
+/** The DragEvent interface is a DOM event that represents a drag and drop interaction. The user initiates a drag by placing a pointer device (such as a mouse) on the touch surface and then dragging the pointer to a new location (such as another DOM element). Applications are free to interpret a drag and drop interaction in an application-specific way. */
interface DragEvent extends MouseEvent {
/**
* Returns the DataTransfer object for the event.
@@ -4730,6 +4787,7 @@
new(type: string, eventInitDict?: DragEventInit): DragEvent;
};
+/** Inherits properties from its parent, AudioNode. */
interface DynamicsCompressorNode extends AudioNode {
readonly attack: AudioParam;
readonly knee: AudioParam;
@@ -4749,6 +4807,7 @@
readonly MIN_EXT: GLenum;
}
+/** The EXT_frag_depth extension is part of the WebGL API and enables to set a depth value of a fragment from within the fragment shader. */
interface EXT_frag_depth {
}
@@ -4762,6 +4821,7 @@
interface EXT_shader_texture_lod {
}
+/** The EXT_texture_filter_anisotropic extension is part of the WebGL API and exposes two constants for anisotropic filtering (AF). */
interface EXT_texture_filter_anisotropic {
readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: GLenum;
readonly TEXTURE_MAX_ANISOTROPY_EXT: GLenum;
@@ -4772,6 +4832,7 @@
"fullscreenerror": Event;
}
+/** Element is the most general base class from which all objects in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element. */
interface Element extends Node, ParentNode, NonDocumentTypeChildNode, ChildNode, Slotable, Animatable {
readonly assignedSlot: HTMLSlotElement | null;
readonly attributes: NamedNodeMap;
@@ -4830,7 +4891,7 @@
/**
* Creates a shadow root for element and returns it.
*/
- attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot;
+ attachShadow(init: ShadowRootInit): ShadowRoot;
/**
* Returns the first (starting at element) inclusive ancestor that matches selectors, and null otherwise.
*/
@@ -4895,8 +4956,14 @@
removeAttributeNode(attr: Attr): Attr;
/**
* Displays element fullscreen and resolves promise when done.
+ * When supplied, options's navigationUI member indicates whether showing
+ * navigation UI while in fullscreen is preferred or not. If set to "show", navigation
+ * simplicity is preferred over screen space, and if set to "hide", more screen space
+ * is preferred. User agents are always free to honor user preference over the application's. The
+ * default value "auto" indicates no application preference.
*/
- requestFullscreen(): Promise<void>;
+ requestFullscreen(options?: FullscreenOptions): Promise<void>;
+ requestPointerLock(): void;
scroll(options?: ScrollToOptions): void;
scroll(x: number, y: number): void;
scrollBy(options?: ScrollToOptions): void;
@@ -4947,6 +5014,7 @@
is?: string;
}
+/** The ErrorEvent interface represents events providing information related to errors in scripts or in files. */
interface ErrorEvent extends Event {
readonly colno: number;
readonly error: any;
@@ -4960,6 +5028,7 @@
new(type: string, eventInitDict?: ErrorEventInit): ErrorEvent;
};
+/** The Event interface represents any event which takes place in the DOM; some are user-generated (such as mouse or keyboard events), while others are generated by APIs (such as events that indicate an animation has finished running, a video has been paused, and so forth). While events are usually triggered by such "external" sources, they can also be triggered programmatically, such as by calling the HTMLElement.click() method of an element, or by defining the event, then sending it to a specified target using EventTarget.dispatchEvent(). There are many types of events, some of which use other interfaces based on the main Event interface. Event itself contains the properties and methods which are common to all events. */
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.
@@ -4985,7 +5054,7 @@
readonly isTrusted: boolean;
returnValue: boolean;
/** @deprecated */
- readonly srcElement: Element | null;
+ readonly srcElement: EventTarget | null;
/**
* Returns the object to which event is dispatched (its target).
*/
@@ -5033,28 +5102,50 @@
handleEvent(evt: Event): void;
}
+interface EventSourceEventMap {
+ "error": Event;
+ "message": MessageEvent;
+ "open": Event;
+}
+
interface EventSource extends EventTarget {
- readonly CLOSED: number;
- readonly CONNECTING: number;
- readonly OPEN: number;
- onerror: (evt: MessageEvent) => any;
- onmessage: (evt: MessageEvent) => any;
- onopen: (evt: MessageEvent) => any;
+ onerror: ((this: EventSource, ev: Event) => any) | null;
+ onmessage: ((this: EventSource, ev: MessageEvent) => any) | null;
+ onopen: ((this: EventSource, ev: Event) => any) | null;
+ /**
+ * Returns the state of this EventSource object's connection. It can have the
+ * values described below.
+ */
readonly readyState: number;
+ /**
+ * Returns the URL providing the event stream.
+ */
readonly url: string;
+ /**
+ * Returns true if the credentials mode
+ * for connection requests to the URL providing the
+ * event stream is set to "include", and false otherwise.
+ */
readonly withCredentials: boolean;
close(): void;
+ readonly CLOSED: number;
+ readonly CONNECTING: number;
+ readonly OPEN: number;
+ addEventListener<K extends keyof EventSourceEventMap>(type: K, listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
+ removeEventListener<K extends keyof EventSourceEventMap>(type: K, listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}
declare var EventSource: {
prototype: EventSource;
new(url: string, eventSourceInitDict?: EventSourceInit): EventSource;
+ readonly CLOSED: number;
+ readonly CONNECTING: number;
+ readonly OPEN: number;
};
-interface EventSourceInit {
- readonly withCredentials: boolean;
-}
-
+/** EventTarget is an interface implemented by objects that can receive events and may have listeners for them. */
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.
@@ -5107,6 +5198,7 @@
IsSearchProviderInstalled(): void;
}
+/** The File interface provides information about files and allows JavaScript in a web page to access their content. */
interface File extends Blob {
readonly lastModified: number;
readonly name: string;
@@ -5117,6 +5209,7 @@
new(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File;
};
+/** An object of this type is returned by the files property of the HTML <input> element; this lets you access the list of files selected with the <input type="file"> element. It's also used for a list of files dropped into web content when using the drag and drop API; see the DataTransfer object for details on this usage. */
interface FileList {
readonly length: number;
item(index: number): File | null;
@@ -5137,6 +5230,7 @@
"progress": ProgressEvent;
}
+/** The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. */
interface FileReader extends EventTarget {
readonly error: DOMException | null;
onabort: ((this: FileReader, ev: ProgressEvent) => any) | null;
@@ -5169,6 +5263,7 @@
readonly LOADING: number;
};
+/** The FocusEvent interface represents focus-related events like focus, blur, focusin, or focusout. */
interface FocusEvent extends UIEvent {
readonly relatedTarget: EventTarget;
initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void;
@@ -5193,6 +5288,7 @@
new(type: string, eventInitDict?: FocusNavigationEventInit): FocusNavigationEvent;
};
+/** The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data". */
interface FormData {
append(name: string, value: string | Blob, fileName?: string): void;
delete(name: string): void;
@@ -5208,6 +5304,7 @@
new(form?: HTMLFormElement): FormData;
};
+/** The GainNode interface represents a change in volume. It is an AudioNode audio-processing module that causes a given gain to be applied to the input data before its propagation to the output. A GainNode always has exactly one input and one output, both with the same number of channels. */
interface GainNode extends AudioNode {
readonly gain: AudioParam;
}
@@ -5217,13 +5314,13 @@
new(context: BaseAudioContext, options?: GainOptions): GainNode;
};
+/** The Gamepad interface of the Gamepad API defines an individual gamepad or other controller, allowing access to information such as button presses, axis positions, and id. */
interface Gamepad {
- readonly axes: number[];
- readonly buttons: GamepadButton[];
+ readonly axes: ReadonlyArray<number>;
+ readonly buttons: ReadonlyArray<GamepadButton>;
readonly connected: boolean;
- readonly displayId: number;
readonly hand: GamepadHand;
- readonly hapticActuators: GamepadHapticActuator[];
+ readonly hapticActuators: ReadonlyArray<GamepadHapticActuator>;
readonly id: string;
readonly index: number;
readonly mapping: GamepadMappingType;
@@ -5236,6 +5333,7 @@
new(): Gamepad;
};
+/** The GamepadButton interface defines an individual button of a gamepad or other controller, allowing access to the current state of different types of buttons available on the control device. */
interface GamepadButton {
readonly pressed: boolean;
readonly touched: boolean;
@@ -5247,15 +5345,17 @@
new(): GamepadButton;
};
+/** The GamepadEvent interface of the Gamepad API contains references to gamepads connected to the system, which is what the gamepad events Window.gamepadconnected and Window.gamepaddisconnected are fired in response to. */
interface GamepadEvent extends Event {
readonly gamepad: Gamepad;
}
declare var GamepadEvent: {
prototype: GamepadEvent;
- new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent;
+ new(type: string, eventInitDict: GamepadEventInit): GamepadEvent;
};
+/** The GamepadHapticActuator interface of the Gamepad API represents hardware in the controller designed to provide haptic feedback to the user (if available), most commonly vibration hardware. */
interface GamepadHapticActuator {
readonly type: GamepadHapticActuatorType;
pulse(value: number, duration: number): Promise<boolean>;
@@ -5266,6 +5366,7 @@
new(): GamepadHapticActuator;
};
+/** The GamepadPose interface of the Gamepad API represents the pose of a WebVR controller at a given timestamp (which includes orientation, position, velocity, and acceleration information.) */
interface GamepadPose {
readonly angularAcceleration: Float32Array | null;
readonly angularVelocity: Float32Array | null;
@@ -5282,16 +5383,13 @@
new(): GamepadPose;
};
+/** The Geolocation interface represents an object able to programmatically obtain the position of the device. It gives Web content access to the location of the device. This allows a Web site or app to offer customized results based on the user's location. */
interface Geolocation {
clearWatch(watchId: number): void;
getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void;
watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number;
}
-interface GetSVGDocument {
- getSVGDocument(): Document;
-}
-
interface GlobalEventHandlersEventMap {
"abort": UIEvent;
"animationcancel": AnimationEvent;
@@ -5356,11 +5454,13 @@
"ratechange": Event;
"reset": Event;
"resize": UIEvent;
- "scroll": UIEvent;
+ "scroll": Event;
"securitypolicyviolation": SecurityPolicyViolationEvent;
"seeked": Event;
"seeking": Event;
- "select": UIEvent;
+ "select": Event;
+ "selectionchange": Event;
+ "selectstart": Event;
"stalled": Event;
"submit": Event;
"suspend": Event;
@@ -5475,7 +5575,7 @@
* Fires when an error occurs during object loading.
* @param ev The event.
*/
- onerror: ErrorEventHandler;
+ onerror: OnErrorEventHandler;
/**
* Fires when the object receives focus.
* @param ev The event.
@@ -5591,7 +5691,7 @@
* 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;
+ onscroll: ((this: GlobalEventHandlers, ev: Event) => any) | null;
onsecuritypolicyviolation: ((this: GlobalEventHandlers, ev: SecurityPolicyViolationEvent) => any) | null;
/**
* Occurs when the seek operation ends.
@@ -5607,7 +5707,9 @@
* Fires when the current selection changes.
* @param ev The event.
*/
- onselect: ((this: GlobalEventHandlers, ev: UIEvent) => any) | null;
+ onselect: ((this: GlobalEventHandlers, ev: Event) => any) | null;
+ onselectionchange: ((this: GlobalEventHandlers, ev: Event) => any) | null;
+ onselectstart: ((this: GlobalEventHandlers, ev: Event) => any) | null;
/**
* Occurs when the download has stopped.
* @param ev The event.
@@ -5675,6 +5777,7 @@
new(): HTMLAllCollection;
};
+/** The HTMLAnchorElement interface represents hyperlink elements and provides special properties and methods (beyond those of the regular HTMLElement object interface that they inherit from) for manipulating the layout and presentation of such elements. */
interface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils {
/**
* Sets or retrieves the character set used to encode the object.
@@ -5783,6 +5886,7 @@
new(): HTMLAppletElement;
};
+/** The HTMLAreaElement interface provides special properties and methods (beyond those of the regular object HTMLElement interface it also has available to it by inheritance) for manipulating the layout and presentation of area elements. */
interface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils {
/**
* Sets or retrieves a text alternative to the graphic.
@@ -5821,6 +5925,7 @@
new(): HTMLAreaElement;
};
+/** The HTMLAudioElement interface provides access to the properties of <audio> elements, as well as methods to manipulate them. It derives from the HTMLMediaElement interface. */
interface HTMLAudioElement extends HTMLMediaElement {
addEventListener<K extends keyof HTMLMediaElementEventMap>(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -5833,6 +5938,7 @@
new(): HTMLAudioElement;
};
+/** The HTMLBRElement interface represents a HTML line break element (<br>). It inherits from HTMLElement. */
interface HTMLBRElement extends HTMLElement {
/**
* Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document.
@@ -5850,6 +5956,7 @@
new(): HTMLBRElement;
};
+/** The HTMLBaseElement interface contains the base URI for a document. This object inherits all of the properties and methods as described in the HTMLElement interface. */
interface HTMLBaseElement extends HTMLElement {
/**
* Gets or sets the baseline URL on which relative links are based.
@@ -5870,6 +5977,7 @@
new(): HTMLBaseElement;
};
+/** The HTMLBaseFontElement interface provides special properties (beyond the regular HTMLElement interface it also has available to it by inheritance) for manipulating <basefont> elements. */
interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty {
/**
* Sets or retrieves the current typeface family.
@@ -5896,6 +6004,7 @@
"orientationchange": Event;
}
+/** The HTMLBodyElement interface provides special properties (beyond those of the regular HTMLElement interface they also inherit) for manipulating body elements. */
interface HTMLBodyElement extends HTMLElement, WindowEventHandlers {
/** @deprecated */
aLink: string;
@@ -5925,6 +6034,7 @@
new(): HTMLBodyElement;
};
+/** The HTMLButtonElement interface provides properties and methods (beyond the <button> object interface it also has available to them by inheritance) for manipulating the layout and presentation of button elements. */
interface HTMLButtonElement extends HTMLElement {
/**
* Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.
@@ -6001,6 +6111,7 @@
new(): HTMLButtonElement;
};
+/** The HTMLCanvasElement interface provides properties and methods for manipulating the layout and presentation of <canvas> elements. The HTMLCanvasElement interface also inherits the properties and methods of the HTMLElement interface. */
interface HTMLCanvasElement extends HTMLElement {
/**
* Gets or sets the height of a canvas element on a document.
@@ -6034,6 +6145,7 @@
new(): HTMLCanvasElement;
};
+/** The HTMLCollection interface represents a generic collection (array-like object similar to arguments) of elements (in document order) and offers methods and properties for selecting from the list. */
interface HTMLCollectionBase {
/**
* Sets or retrieves the number of objects in a collection.
@@ -6064,6 +6176,7 @@
[index: number]: T;
}
+/** The HTMLDListElement interface provides special properties (beyond those of the regular HTMLElement interface it also has available to it by inheritance) for manipulating definition list elements. */
interface HTMLDListElement extends HTMLElement {
/** @deprecated */
compact: boolean;
@@ -6078,6 +6191,7 @@
new(): HTMLDListElement;
};
+/** The HTMLDataElement interface provides special properties (beyond the regular HTMLElement interface it also has available to it by inheritance) for manipulating <data> elements. */
interface HTMLDataElement extends HTMLElement {
value: string;
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
@@ -6091,6 +6205,7 @@
new(): HTMLDataElement;
};
+/** The HTMLDataListElement interface provides special properties (beyond the HTMLElement object interface it also has available to it by inheritance) to manipulate <datalist> elements and their content. */
interface HTMLDataListElement extends HTMLElement {
readonly options: HTMLCollectionOf<HTMLOptionElement>;
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
@@ -6148,6 +6263,7 @@
new(): HTMLDirectoryElement;
};
+/** The HTMLDivElement interface provides special properties (beyond the regular HTMLElement interface it also has available to it by inheritance) for manipulating <div> elements. */
interface HTMLDivElement extends HTMLElement {
/**
* Sets or retrieves how the object is aligned with adjacent text.
@@ -6165,6 +6281,7 @@
new(): HTMLDivElement;
};
+/** The HTMLDocument property of Window objects is an alias that browsers expose for the Document interface object. */
interface HTMLDocument extends Document {
addEventListener<K extends keyof DocumentEventMap>(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -6180,6 +6297,7 @@
interface HTMLElementEventMap extends ElementEventMap, GlobalEventHandlersEventMap, DocumentAndElementEventHandlersEventMap {
}
+/** The HTMLElement interface represents any HTML element. Some elements directly implement this interface, others implement it via an interface that inherits it. */
interface HTMLElement extends Element, GlobalEventHandlers, DocumentAndElementEventHandlers, ElementContentEditable, HTMLOrSVGElement, ElementCSSInlineStyle {
accessKey: string;
readonly accessKeyLabel: string;
@@ -6209,56 +6327,29 @@
new(): HTMLElement;
};
-interface HTMLEmbedElement extends HTMLElement, GetSVGDocument {
+/** The HTMLEmbedElement interface, which provides special properties (beyond the regular HTMLElement interface it also has available to it by inheritance) for manipulating <embed> elements. */
+interface HTMLEmbedElement extends HTMLElement {
/** @deprecated */
align: string;
/**
* Sets or retrieves the height of the object.
*/
height: string;
- hidden: any;
- /**
- * Gets or sets whether the DLNA PlayTo device is available.
- */
- msPlayToDisabled: boolean;
- /**
- * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.
- */
- 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.
*/
/** @deprecated */
name: string;
/**
- * Retrieves the palette used for the embedded document.
- */
- readonly palette: string;
- /**
- * Retrieves the URL of the plug-in used to view an embedded document.
- */
- readonly pluginspage: string;
- readonly readyState: string;
- /**
* Sets or retrieves a URL to be loaded by the object.
*/
src: string;
- /**
- * Sets or retrieves the height and width units of the embed object.
- */
- units: string;
+ type: string;
/**
* Sets or retrieves the width of the object.
*/
width: string;
+ getSVGDocument(): Document | null;
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
removeEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
@@ -6270,6 +6361,7 @@
new(): HTMLEmbedElement;
};
+/** The HTMLFieldSetElement interface has special properties and methods (beyond the regular HTMLElement interface it also has available to it by inheritance) for manipulating the layout and presentation of field-set elements. */
interface HTMLFieldSetElement extends HTMLElement {
disabled: boolean;
readonly elements: HTMLCollection;
@@ -6312,6 +6404,7 @@
new(): HTMLFieldSetElement;
};
+/** Implements the document object model (DOM) representation of the font element. The HTML Font Element <font> defines the font size, font face and color of text. */
interface HTMLFontElement extends HTMLElement {
/** @deprecated */
color: string;
@@ -6333,6 +6426,7 @@
new(): HTMLFontElement;
};
+/** The HTMLFormControlsCollection interface represents a collection of HTML form control elements. */
interface HTMLFormControlsCollection extends HTMLCollectionBase {
/**
* element = collection[name]
@@ -6345,6 +6439,7 @@
new(): HTMLFormControlsCollection;
};
+/** The HTMLFormElement interface represents a <form> element in the DOM; it allows access to and in some cases modification of aspects of the form, as well as access to its component elements. */
interface HTMLFormElement extends HTMLElement {
/**
* Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form.
@@ -6481,6 +6576,7 @@
interface HTMLFrameSetElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap {
}
+/** The HTMLFrameSetElement interface provides special properties (beyond those of the regular HTMLElement interface they also inherit) for manipulating <frameset> elements. */
interface HTMLFrameSetElement extends HTMLElement, WindowEventHandlers {
/**
* Sets or retrieves the frame widths of the object.
@@ -6503,6 +6599,7 @@
new(): HTMLFrameSetElement;
};
+/** The HTMLHRElement interface provides special properties (beyond those of the HTMLElement interface it also has available to it by inheritance) for manipulating <hr> elements. */
interface HTMLHRElement extends HTMLElement {
/**
* Sets or retrieves how the object is aligned with adjacent text.
@@ -6534,6 +6631,7 @@
new(): HTMLHRElement;
};
+/** The HTMLHeadElement interface contains the descriptive information, or metadata, for a document. This object inherits all of the properties and methods described in the HTMLElement interface. */
interface HTMLHeadElement extends HTMLElement {
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -6546,6 +6644,7 @@
new(): HTMLHeadElement;
};
+/** The HTMLHeadingElement interface represents the different heading elements. It inherits methods and properties from the HTMLElement interface. */
interface HTMLHeadingElement extends HTMLElement {
/**
* Sets or retrieves a value that indicates the table alignment.
@@ -6563,6 +6662,7 @@
new(): HTMLHeadingElement;
};
+/** The HTMLHtmlElement interface serves as the root node for a given HTML document. This object inherits the properties and methods described in the HTMLElement interface. */
interface HTMLHtmlElement extends HTMLElement {
/**
* Sets or retrieves the DTD version that governs the current document.
@@ -6594,12 +6694,14 @@
username: string;
}
-interface HTMLIFrameElement extends HTMLElement, GetSVGDocument {
+/** The HTMLIFrameElement interface provides special properties and methods (beyond those of the HTMLElement interface it also has available to it by inheritance) for manipulating the layout and presentation of inline frame elements. */
+interface HTMLIFrameElement extends HTMLElement {
/**
* Sets or retrieves how the object is aligned with adjacent text.
*/
/** @deprecated */
align: string;
+ allow: string;
allowFullscreen: boolean;
allowPaymentRequest: boolean;
/**
@@ -6609,7 +6711,7 @@
/**
* Retrieves the object of the specified.
*/
- readonly contentWindow: Window | null;
+ readonly contentWindow: WindowProxy | null;
/**
* Sets or retrieves whether to display a border for the frame.
*/
@@ -6638,7 +6740,7 @@
* Sets or retrieves the frame name.
*/
name: string;
- readonly referrerPolicy: ReferrerPolicy;
+ referrerPolicy: ReferrerPolicy;
readonly sandbox: DOMTokenList;
/**
* Sets or retrieves whether the frame can be scrolled.
@@ -6657,6 +6759,7 @@
* Sets or retrieves the width of the object.
*/
width: string;
+ getSVGDocument(): Document | null;
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLIFrameElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
removeEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLIFrameElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
@@ -6668,6 +6771,7 @@
new(): HTMLIFrameElement;
};
+/** The HTMLImageElement interface provides special properties and methods  for manipulating the layout and presentation of <img> elements. */
interface HTMLImageElement extends HTMLElement {
/**
* Sets or retrieves how the object is aligned with adjacent text.
@@ -6757,6 +6861,7 @@
new(): HTMLImageElement;
};
+/** The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements. */
interface HTMLInputElement extends HTMLElement {
/**
* Sets or retrieves a comma-separated list of content types.
@@ -6961,6 +7066,7 @@
new(): HTMLInputElement;
};
+/** The HTMLLIElement interface exposes specific properties and methods (beyond those defined by regular HTMLElement interface it also has available to it by inheritance) for manipulating list elements. */
interface HTMLLIElement extends HTMLElement {
/** @deprecated */
type: string;
@@ -6979,6 +7085,7 @@
new(): HTMLLIElement;
};
+/** The HTMLLabelElement interface gives access to properties specific to <label> elements. It inherits methods and properties from the base HTMLElement interface. */
interface HTMLLabelElement extends HTMLElement {
readonly control: HTMLElement | null;
/**
@@ -7000,6 +7107,7 @@
new(): HTMLLabelElement;
};
+/** The HTMLLegendElement is an interface allowing to access properties of the <legend> elements. It inherits properties and methods from the HTMLElement interface. */
interface HTMLLegendElement extends HTMLElement {
/** @deprecated */
align: string;
@@ -7018,6 +7126,7 @@
new(): HTMLLegendElement;
};
+/** The HTMLLinkElement interface represents reference information for external resources and the relationship of those resources to a document and vice-versa. This object inherits all of the properties and methods of the HTMLElement interface. */
interface HTMLLinkElement extends HTMLElement, LinkStyle {
as: string;
/**
@@ -7084,6 +7193,7 @@
new(): HTMLMainElement;
};
+/** The HTMLMapElement interface provides special properties and methods (beyond those of the regular object HTMLElement interface it also has available to it by inheritance) for manipulating the layout and presentation of map elements. */
interface HTMLMapElement extends HTMLElement {
/**
* Retrieves a collection of the area objects defined for the given map object.
@@ -7110,6 +7220,7 @@
"start": Event;
}
+/** The HTMLMarqueeElement interface provides methods to manipulate <marquee> elements. */
interface HTMLMarqueeElement extends HTMLElement {
/** @deprecated */
behavior: string;
@@ -7157,8 +7268,10 @@
interface HTMLMediaElementEventMap extends HTMLElementEventMap {
"encrypted": MediaEncryptedEvent;
"msneedkey": Event;
+ "waitingforkey": Event;
}
+/** The HTMLMediaElement interface adds to HTMLElement the properties and methods needed to support basic media-related capabilities that are common to audio and video. */
interface HTMLMediaElement extends HTMLElement {
/**
* Returns an AudioTrackList object with the audio tracks for a given video element.
@@ -7252,6 +7365,7 @@
onencrypted: ((this: HTMLMediaElement, ev: MediaEncryptedEvent) => any) | null;
/** @deprecated */
onmsneedkey: ((this: HTMLMediaElement, ev: Event) => any) | null;
+ onwaitingforkey: ((this: HTMLMediaElement, ev: Event) => any) | null;
/**
* Gets a flag that specifies whether playback is paused.
*/
@@ -7364,6 +7478,7 @@
new(): HTMLMenuElement;
};
+/** The HTMLMetaElement interface contains descriptive metadata about a document. It inherits all of the properties and methods described in the HTMLElement interface. */
interface HTMLMetaElement extends HTMLElement {
/**
* Gets or sets meta-information to associate with httpEquiv or name.
@@ -7393,6 +7508,7 @@
new(): HTMLMetaElement;
};
+/** The HTML <meter> elements expose the HTMLMeterElement interface, which provides special properties and methods (beyond the HTMLElement object interface they also have available to them by inheritance) for manipulating the layout and presentation of <meter> elements. */
interface HTMLMeterElement extends HTMLElement {
high: number;
readonly labels: NodeListOf<HTMLLabelElement>;
@@ -7412,6 +7528,7 @@
new(): HTMLMeterElement;
};
+/** The HTMLModElement interface provides special properties (beyond the regular methods and properties available through the HTMLElement interface they also have available to them by inheritance) for manipulating modification elements, that is <del> and <ins>. */
interface HTMLModElement extends HTMLElement {
/**
* Sets or retrieves reference information about the object.
@@ -7432,6 +7549,7 @@
new(): HTMLModElement;
};
+/** The HTMLOListElement interface provides special properties (beyond those defined on the regular HTMLElement interface it also has available to it by inheritance) for manipulating ordered list elements. */
interface HTMLOListElement extends HTMLElement {
/** @deprecated */
compact: boolean;
@@ -7452,11 +7570,8 @@
new(): HTMLOListElement;
};
-interface HTMLObjectElement extends HTMLElement, GetSVGDocument {
- /**
- * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element.
- */
- readonly BaseHref: string;
+/** The HTMLObjectElement interface provides special properties and methods (beyond those on the HTMLElement interface it also has available to it by inheritance) for manipulating the layout and presentation of <object> element, representing external resources. */
+interface HTMLObjectElement extends HTMLElement {
/** @deprecated */
align: string;
/**
@@ -7485,6 +7600,7 @@
* Retrieves the document object of the page or frame.
*/
readonly contentDocument: Document | null;
+ readonly contentWindow: WindowProxy | null;
/**
* Sets or retrieves the URL that references the data of the object.
*/
@@ -7502,26 +7618,9 @@
/** @deprecated */
hspace: number;
/**
- * Gets or sets whether the DLNA PlayTo device is available.
- */
- msPlayToDisabled: boolean;
- /**
- * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.
- */
- 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.
*/
name: string;
- readonly readyState: number;
/**
* Sets or retrieves a message to be displayed while an object is loading.
*/
@@ -7531,7 +7630,7 @@
* Sets or retrieves the MIME type of the object.
*/
type: string;
- typemustmatch: boolean;
+ typeMustMatch: boolean;
/**
* Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map.
*/
@@ -7558,6 +7657,7 @@
* Returns whether a form will validate when it is submitted, without having to submit it.
*/
checkValidity(): boolean;
+ getSVGDocument(): Document | null;
reportValidity(): boolean;
/**
* Sets a custom error message that is displayed when a form is submitted.
@@ -7575,6 +7675,7 @@
new(): HTMLObjectElement;
};
+/** The HTMLOptGroupElement interface provides special properties and methods (beyond the regular HTMLElement object interface they also have available to them by inheritance) for manipulating the layout and presentation of <optgroup> elements. */
interface HTMLOptGroupElement extends HTMLElement {
disabled: boolean;
/**
@@ -7596,6 +7697,7 @@
new(): HTMLOptGroupElement;
};
+/** The HTMLOptionElement interface represents <option> elements and inherits all classes and methods of the HTMLElement interface. */
interface HTMLOptionElement extends HTMLElement {
/**
* Sets or retrieves the status of an option.
@@ -7637,6 +7739,7 @@
new(): HTMLOptionElement;
};
+/** HTMLOptionsCollection is an interface representing a collection of HTML option elements (in document order) and offers methods and properties for traversing the list as well as optionally altering its items. This type is returned solely by the "options" property of select. */
interface HTMLOptionsCollection extends HTMLCollectionOf<HTMLOptionElement> {
/**
* Returns the number of elements in the collection.
@@ -7672,12 +7775,13 @@
interface HTMLOrSVGElement {
readonly dataset: DOMStringMap;
- nonce: string;
+ nonce?: string;
tabIndex: number;
blur(): void;
focus(options?: FocusOptions): void;
}
+/** The HTMLOutputElement interface provides properties and methods (beyond those inherited from HTMLElement) for manipulating the layout and presentation of <output> elements. */
interface HTMLOutputElement extends HTMLElement {
defaultValue: string;
readonly form: HTMLFormElement | null;
@@ -7703,6 +7807,7 @@
new(): HTMLOutputElement;
};
+/** The HTMLParagraphElement interface provides special properties (beyond those of the regular HTMLElement object interface it inherits) for manipulating <p> elements. */
interface HTMLParagraphElement extends HTMLElement {
/**
* Sets or retrieves how the object is aligned with adjacent text.
@@ -7720,6 +7825,7 @@
new(): HTMLParagraphElement;
};
+/** The HTMLParamElement interface provides special properties (beyond those of the regular HTMLElement object interface it inherits) for manipulating <param> elements, representing a pair of a key and a value that acts as a parameter for an <object> element. */
interface HTMLParamElement extends HTMLElement {
/**
* Sets or retrieves the name of an input parameter for an element.
@@ -7750,6 +7856,7 @@
new(): HTMLParamElement;
};
+/** The HTMLPictureElement interface represents a <picture> HTML element. It doesn't implement specific properties or methods. */
interface HTMLPictureElement extends HTMLElement {
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -7762,6 +7869,7 @@
new(): HTMLPictureElement;
};
+/** The HTMLPreElement interface expose specific properties and methods (beyond those defined by regular HTMLElement interface it also has available to it by inheritance) for manipulating block of preformatted text. */
interface HTMLPreElement extends HTMLElement {
/**
* Sets or gets a value that you can use to implement your own width functionality for the object.
@@ -7779,6 +7887,7 @@
new(): HTMLPreElement;
};
+/** The HTMLProgressElement interface provides special properties and methods (beyond the regular HTMLElement interface it also has available to it by inheritance) for manipulating the layout and presentation of <progress> elements. */
interface HTMLProgressElement extends HTMLElement {
readonly labels: NodeListOf<HTMLLabelElement>;
/**
@@ -7804,6 +7913,7 @@
new(): HTMLProgressElement;
};
+/** The HTMLQuoteElement interface provides special properties and methods (beyond the regular HTMLElement interface it also has available to it by inheritance) for manipulating quoting elements, like <blockquote> and <q>, but not the <cite> element. */
interface HTMLQuoteElement extends HTMLElement {
/**
* Sets or retrieves reference information about the object.
@@ -7820,6 +7930,7 @@
new(): HTMLQuoteElement;
};
+/** HTML <script> elements expose the HTMLScriptElement interface, which provides special properties and methods for manipulating the behavior and execution of <script> elements (beyond the inherited HTMLElement interface). */
interface HTMLScriptElement extends HTMLElement {
async: boolean;
/**
@@ -7868,6 +7979,7 @@
new(): HTMLScriptElement;
};
+/** The HTMLSelectElement interface represents a <select> HTML Element. These elements also share all of the properties and methods of other HTML elements via the HTMLElement interface. */
interface HTMLSelectElement extends HTMLElement {
autocomplete: string;
/**
@@ -7986,6 +8098,7 @@
new(): HTMLSlotElement;
};
+/** The HTMLSourceElement interface provides special properties (beyond the regular HTMLElement object interface it also has available to it by inheritance) for manipulating <source> elements. */
interface HTMLSourceElement extends HTMLElement {
/**
* Gets or sets the intended media type of the media source.
@@ -8012,6 +8125,7 @@
new(): HTMLSourceElement;
};
+/** The HTMLSpanElement interface represents a <span> element and derives from the HTMLElement interface, but without implementing any additional properties or methods. */
interface HTMLSpanElement extends HTMLElement {
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -8024,6 +8138,7 @@
new(): HTMLSpanElement;
};
+/** The HTMLStyleElement interface represents a <style> element. It inherits properties and methods from its parent, HTMLElement, and from LinkStyle. */
interface HTMLStyleElement extends HTMLElement, LinkStyle {
/**
* Sets or retrieves the media type.
@@ -8045,6 +8160,7 @@
new(): HTMLStyleElement;
};
+/** The HTMLTableCaptionElement interface special properties (beyond the regular HTMLElement interface it also has available to it by inheritance) for manipulating table caption elements. */
interface HTMLTableCaptionElement extends HTMLElement {
/**
* Sets or retrieves the alignment of the caption or legend.
@@ -8062,6 +8178,7 @@
new(): HTMLTableCaptionElement;
};
+/** The HTMLTableCellElement interface provides special properties and methods (beyond the regular HTMLElement interface it also has available to it by inheritance) for manipulating the layout and presentation of table cells, either header or data cells, in an HTML document. */
interface HTMLTableCellElement extends HTMLElement {
/**
* Sets or retrieves abbreviated text for the object.
@@ -8131,6 +8248,7 @@
new(): HTMLTableCellElement;
};
+/** The HTMLTableColElement interface provides special properties (beyond the HTMLElement interface it also has available to it inheritance) for manipulating single or grouped table column elements. */
interface HTMLTableColElement extends HTMLElement {
/**
* Sets or retrieves the alignment of the object relative to the display or table.
@@ -8175,6 +8293,7 @@
new(): HTMLTableDataCellElement;
};
+/** The HTMLTableElement interface provides special properties and methods (beyond the regular HTMLElement object interface it also has available to it by inheritance) for manipulating the layout and presentation of tables in an HTML document. */
interface HTMLTableElement extends HTMLElement {
/**
* Sets or retrieves a value that indicates the table alignment.
@@ -8300,6 +8419,7 @@
new(): HTMLTableHeaderCellElement;
};
+/** The HTMLTableRowElement interface provides special properties and methods (beyond the HTMLElement interface it also has available to it by inheritance) for manipulating the layout and presentation of rows in an HTML table. */
interface HTMLTableRowElement extends HTMLElement {
/**
* Sets or retrieves how the object is aligned with adjacent text.
@@ -8347,6 +8467,7 @@
new(): HTMLTableRowElement;
};
+/** The HTMLTableSectionElement interface provides special properties and methods (beyond the HTMLElement interface it also has available to it by inheritance) for manipulating the layout and presentation of sections, that is headers, footers and bodies, in an HTML table. */
interface HTMLTableSectionElement extends HTMLElement {
/**
* Sets or retrieves a value that indicates the table alignment.
@@ -8384,6 +8505,7 @@
new(): HTMLTableSectionElement;
};
+/** The HTMLTemplateElement interface enables access to the contents of an HTML <template> element. */
interface HTMLTemplateElement extends HTMLElement {
readonly content: DocumentFragment;
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
@@ -8397,6 +8519,7 @@
new(): HTMLTemplateElement;
};
+/** The HTMLTextAreaElement interface provides special properties and methods for manipulating the layout and presentation of <textarea> elements. */
interface HTMLTextAreaElement extends HTMLElement {
autocomplete: string;
/**
@@ -8511,6 +8634,7 @@
new(): HTMLTextAreaElement;
};
+/** The HTMLTimeElement interface provides special properties (beyond the regular HTMLElement interface it also has available to it by inheritance) for manipulating <time> elements. */
interface HTMLTimeElement extends HTMLElement {
dateTime: string;
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
@@ -8524,6 +8648,7 @@
new(): HTMLTimeElement;
};
+/** The HTMLTitleElement interface contains the title for a document. This element inherits all of the properties and methods of the HTMLElement interface. */
interface HTMLTitleElement extends HTMLElement {
/**
* Retrieves or sets the text of the object as a string.
@@ -8540,6 +8665,7 @@
new(): HTMLTitleElement;
};
+/** The HTMLTrackElement */
interface HTMLTrackElement extends HTMLElement {
default: boolean;
kind: string;
@@ -8567,6 +8693,7 @@
readonly NONE: number;
};
+/** The HTMLUListElement interface provides special properties (beyond those defined on the regular HTMLElement interface it also has available to it by inheritance) for manipulating unordered list elements. */
interface HTMLUListElement extends HTMLElement {
/** @deprecated */
compact: boolean;
@@ -8583,6 +8710,7 @@
new(): HTMLUListElement;
};
+/** The HTMLUnknownElement interface represents an invalid HTML element and derives from the HTMLElement interface, but without implementing any additional properties or methods. */
interface HTMLUnknownElement extends HTMLElement {
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -8601,6 +8729,7 @@
"MSVideoOptimalLayoutChanged": Event;
}
+/** The HTMLVideoElement interface provides special properties and methods for manipulating video objects. It also inherits properties and methods of HTMLMediaElement and HTMLElement. */
interface HTMLVideoElement extends HTMLMediaElement {
/**
* Gets or sets the height of the video element.
@@ -8652,6 +8781,7 @@
new(): HTMLVideoElement;
};
+/** The HashChangeEvent event is fired when the fragment identifier of the URL has changed (the part of the URL that follows the # symbol, including the # symbol). */
interface HashChangeEvent extends Event {
readonly newURL: string;
readonly oldURL: string;
@@ -8662,6 +8792,7 @@
new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent;
};
+/** The Headers interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing. A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.  You can add to this using methods like append() (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence. */
interface Headers {
append(name: string, value: string): void;
delete(name: string): void;
@@ -8676,6 +8807,7 @@
new(init?: HeadersInit): Headers;
};
+/** The History interface allows manipulation of the browser session history, that is the pages visited in the tab or frame that the current page is loaded in. */
interface History {
readonly length: number;
scrollRestoration: ScrollRestoration;
@@ -8701,6 +8833,7 @@
interface IDBArrayKey extends Array<IDBValidKey> {
}
+/** The IDBCursor interface of the IndexedDB API represents a cursor for traversing or iterating over multiple records in a database. */
interface IDBCursor {
/**
* Returns the direction ("next", "nextunique", "prev" or "prevunique")
@@ -8711,12 +8844,12 @@
* Returns the key of the cursor.
* Throws a "InvalidStateError" DOMException if the cursor is advancing or is finished.
*/
- readonly key: IDBValidKey | IDBKeyRange;
+ readonly key: IDBValidKey;
/**
* Returns the effective key of the cursor.
* Throws a "InvalidStateError" DOMException if the cursor is advancing or is finished.
*/
- readonly primaryKey: IDBValidKey | IDBKeyRange;
+ readonly primaryKey: IDBValidKey;
/**
* Returns the IDBObjectStore or IDBIndex the cursor was opened from.
*/
@@ -8730,12 +8863,12 @@
* Advances the cursor to the next record in range matching or
* after key.
*/
- continue(key?: IDBValidKey | IDBKeyRange): void;
+ continue(key?: IDBValidKey): void;
/**
* Advances the cursor to the next record in range matching
* or after key and primaryKey. Throws an "InvalidAccessError" DOMException if the source is not an index.
*/
- continuePrimaryKey(key: IDBValidKey | IDBKeyRange, primaryKey: IDBValidKey | IDBKeyRange): void;
+ continuePrimaryKey(key: IDBValidKey, primaryKey: IDBValidKey): void;
/**
* Delete the record pointed at by the cursor with a new value.
* If successful, request's result will be undefined.
@@ -8754,6 +8887,7 @@
new(): IDBCursor;
};
+/** The IDBCursorWithValue interface of the IndexedDB API represents a cursor for traversing or iterating over multiple records in a database. It is the same as the IDBCursor, except that it includes the value property. */
interface IDBCursorWithValue extends IDBCursor {
/**
* Returns the cursor's current value.
@@ -8773,6 +8907,7 @@
"versionchange": IDBVersionChangeEvent;
}
+/** The IDBDatabase interface of the IndexedDB API provides a connection to a database; you can use an IDBDatabase object to open a transaction on your database then create, manipulate, and delete objects (data) in that database. The interface provides the only way to get and manage versions of the database. */
interface IDBDatabase extends EventTarget {
/**
* Returns the name of the database.
@@ -8824,6 +8959,7 @@
readonly indexedDB: IDBFactory;
}
+/** In the following code snippet, we make a request to open a database, and include handlers for the success and error cases. For a full working example, see our To-do Notifications app (view example live.) */
interface IDBFactory {
/**
* Compares two values as keys. Returns -1 if key1 precedes key2, 1 if key2 precedes key1, and 0 if
@@ -8853,6 +8989,7 @@
new(): IDBFactory;
};
+/** IDBIndex interface of the IndexedDB API provides asynchronous access to an index in a database. An index is a kind of object store for looking up records in another object store, called the referenced object store. You use this interface to retrieve data. */
interface IDBIndex {
readonly keyPath: string | string[];
readonly multiEntry: boolean;
@@ -8913,6 +9050,7 @@
new(): IDBIndex;
};
+/** A key range can be a single value or a range with upper and lower bounds or endpoints. If the key range has both upper and lower bounds, then it is bounded; if it has no bounds, it is unbounded. A bounded key range can either be open (the endpoints are excluded) or closed (the endpoints are included). To retrieve all keys within a certain range, you can use the following code constructs: */
interface IDBKeyRange {
/**
* Returns lower bound, or undefined if none.
@@ -8961,6 +9099,7 @@
upperBound(upper: any, open?: boolean): IDBKeyRange;
};
+/** This example shows a variety of different uses of object stores, from updating the data structure with IDBObjectStore.createIndex inside an onupgradeneeded function, to adding a new item to our object store with IDBObjectStore.add. For a full working example, see our To-do Notifications app (view example live.) */
interface IDBObjectStore {
/**
* Returns true if the store has a key generator, and false otherwise.
@@ -8984,7 +9123,7 @@
* Returns the associated transaction.
*/
readonly transaction: IDBTransaction;
- add(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest<IDBValidKey>;
+ add(value: any, key?: IDBValidKey): IDBRequest<IDBValidKey>;
/**
* Deletes all records in store.
* If successful, request's result will
@@ -9057,7 +9196,7 @@
* null if there were no matching records.
*/
openKeyCursor(query?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest<IDBCursor | null>;
- put(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest<IDBValidKey>;
+ put(value: any, key?: IDBValidKey): IDBRequest<IDBValidKey>;
}
declare var IDBObjectStore: {
@@ -9070,6 +9209,7 @@
"upgradeneeded": IDBVersionChangeEvent;
}
+/** Also inherits methods from its parents IDBRequest and EventTarget. */
interface IDBOpenDBRequest extends IDBRequest<IDBDatabase> {
onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null;
onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null;
@@ -9089,6 +9229,7 @@
"success": Event;
}
+/** The request object does not initially contain any information about the result of the operation, but once information becomes available, an event is fired on the request, and the information becomes available through the properties of the IDBRequest instance. */
interface IDBRequest<T = any> extends EventTarget {
/**
* When a request is completed, returns the error (a DOMException), or null if the request succeeded. Throws
@@ -9180,6 +9321,7 @@
new(): IDBTransaction;
};
+/** The IDBVersionChangeEvent interface of the IndexedDB API indicates that the version of the database has changed, as the result of an IDBOpenDBRequest.onupgradeneeded event handler function. */
interface IDBVersionChangeEvent extends Event {
readonly newVersion: number | null;
readonly oldVersion: number;
@@ -9190,6 +9332,7 @@
new(type: string, eventInitDict?: IDBVersionChangeEventInit): IDBVersionChangeEvent;
};
+/** The IIRFilterNode interface of the Web Audio API is a AudioNode processor which implements a general infinite impulse response (IIR)  filter; this type of filter can be used to implement tone control devices and graphic equalizers as well. It lets the parameters of the filter response be specified, so that it can be tuned as needed. */
interface IIRFilterNode extends AudioNode {
getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void;
}
@@ -9248,6 +9391,7 @@
new(): ImageBitmapRenderingContext;
};
+/** The ImageData interface represents the underlying pixel data of an area of a <canvas> element. It is created using the ImageData() constructor or creator methods on the CanvasRenderingContext2D object associated with a canvas: createImageData() and getImageData(). It can also be used to set a part of the canvas by using putImageData(). */
interface ImageData {
/**
* Returns the one-dimensional array containing the data in RGBA order, as integers in the
@@ -9268,6 +9412,7 @@
new(array: Uint8ClampedArray, width: number, height: number): ImageData;
};
+/** The IntersectionObserver interface of the Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport. */
interface IntersectionObserver {
readonly root: Element | null;
readonly rootMargin: string;
@@ -9283,6 +9428,7 @@
new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver;
};
+/** The IntersectionObserverEntry interface of the Intersection Observer API describes the intersection between the target element and its root container at a specific moment of transition. */
interface IntersectionObserverEntry {
readonly boundingClientRect: ClientRect | DOMRect;
readonly intersectionRatio: number;
@@ -9298,6 +9444,7 @@
new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry;
};
+/** KeyboardEvent objects describe a user interaction with the keyboard; each event describes a single interaction between the user and a key (or combination of a key with modifier keys) on the keyboard. */
interface KeyboardEvent extends UIEvent {
readonly altKey: boolean;
/** @deprecated */
@@ -9365,6 +9512,7 @@
new(): ListeningStateChangedEvent;
};
+/** The Location interface represents the location (URL) of the object it is linked to. Changes done on it are reflected on the object it relates to. Both the Document and Window interface have such a linked Location, accessible via Document.location and Window.location respectively. */
interface Location {
/**
* Returns a DOMStringList object listing the origins of the ancestor browsing contexts, from the parent browsing
@@ -9505,6 +9653,7 @@
new(): MSGesture;
};
+/** The MSGestureEvent is a proprietary interface specific to Internet Explorer and Microsoft Edge which represents events that occur due to touch gestures. Events using this interface include MSGestureStart, MSGestureEnd, MSGestureTap, MSGestureHold, MSGestureChange, and MSInertiaStart. */
interface MSGestureEvent extends UIEvent {
readonly clientX: number;
readonly clientY: number;
@@ -9541,6 +9690,7 @@
readonly MSGESTURE_FLAG_NONE: number;
};
+/** The msGraphicsTrust() constructor returns an object that provides properties for info on protected video playback. */
interface MSGraphicsTrust {
readonly constrictionActive: boolean;
readonly status: string;
@@ -9688,6 +9838,7 @@
new(): MSStream;
};
+/** The MediaDevicesInfo interface contains information that describes a single media input or output device. */
interface MediaDeviceInfo {
readonly deviceId: string;
readonly groupId: string;
@@ -9704,6 +9855,7 @@
"devicechange": Event;
}
+/** The MediaDevices interface provides access to connected media input devices like cameras and microphones, as well as screen sharing. In essence, it lets you obtain access to any hardware source of media data. */
interface MediaDevices extends EventTarget {
ondevicechange: ((this: MediaDevices, ev: Event) => any) | null;
enumerateDevices(): Promise<MediaDeviceInfo[]>;
@@ -9720,6 +9872,7 @@
new(): MediaDevices;
};
+/** A MediaElementSourceNode has no inputs and exactly one output, and is created using the AudioContext.createMediaElementSource method. The amount of channels in the output equals the number of channels of the audio referenced by the HTMLMediaElement used in the creation of the node, or is 1 if the HTMLMediaElement has no audio. */
interface MediaElementAudioSourceNode extends AudioNode {
readonly mediaElement: HTMLMediaElement;
}
@@ -9739,6 +9892,7 @@
new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent;
};
+/** The MediaError interface represents an error which occurred while handling media in an HTML media element based on HTMLMediaElement, such as <audio> or <video>. */
interface MediaError {
readonly code: number;
readonly message: string;
@@ -9760,6 +9914,7 @@
readonly MS_MEDIA_ERR_ENCRYPTED: number;
};
+/** The MediaKeyMessageEvent interface of the EncryptedMediaExtensions API contains the content and related data when the content decryption module generates a message for the session. */
interface MediaKeyMessageEvent extends Event {
readonly message: ArrayBuffer;
readonly messageType: MediaKeyMessageType;
@@ -9767,19 +9922,31 @@
declare var MediaKeyMessageEvent: {
prototype: MediaKeyMessageEvent;
- new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent;
+ new(type: string, eventInitDict: MediaKeyMessageEventInit): MediaKeyMessageEvent;
};
+interface MediaKeySessionEventMap {
+ "keystatuseschange": Event;
+ "message": MessageEvent;
+}
+
+/** The MediaKeySession interface of the EncryptedMediaExtensions API represents a context for message exchange with a content decryption module (CDM). */
interface MediaKeySession extends EventTarget {
readonly closed: Promise<void>;
readonly expiration: number;
readonly keyStatuses: MediaKeyStatusMap;
+ onkeystatuseschange: ((this: MediaKeySession, ev: Event) => any) | null;
+ onmessage: ((this: MediaKeySession, ev: MessageEvent) => any) | null;
readonly sessionId: string;
close(): Promise<void>;
- generateRequest(initDataType: string, initData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise<void>;
+ generateRequest(initDataType: string, initData: BufferSource): Promise<void>;
load(sessionId: string): Promise<boolean>;
remove(): Promise<void>;
- update(response: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise<void>;
+ update(response: BufferSource): Promise<void>;
+ addEventListener<K extends keyof MediaKeySessionEventMap>(type: K, listener: (this: MediaKeySession, ev: MediaKeySessionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
+ removeEventListener<K extends keyof MediaKeySessionEventMap>(type: K, listener: (this: MediaKeySession, ev: MediaKeySessionEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}
declare var MediaKeySession: {
@@ -9787,11 +9954,12 @@
new(): MediaKeySession;
};
+/** The MediaKeyStatusMap interface of the EncryptedMediaExtensions API is a read-only map of media key statuses by key IDs. */
interface MediaKeyStatusMap {
readonly size: number;
- forEach(callback: Function, thisArg?: any): void;
- get(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): MediaKeyStatus;
- has(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): boolean;
+ get(keyId: BufferSource): any;
+ has(keyId: BufferSource): boolean;
+ forEach(callbackfn: (value: MediaKeyStatus, key: BufferSource, parent: MediaKeyStatusMap) => void, thisArg?: any): void;
}
declare var MediaKeyStatusMap: {
@@ -9799,6 +9967,7 @@
new(): MediaKeyStatusMap;
};
+/** The MediaKeySystemAccess interface of the EncryptedMediaExtensions API provides access to a Key System for decryption and/or a content protection provider. You can request an instance of this object using the Navigator.requestMediaKeySystemAccess method. */
interface MediaKeySystemAccess {
readonly keySystem: string;
createMediaKeys(): Promise<MediaKeys>;
@@ -9810,9 +9979,10 @@
new(): MediaKeySystemAccess;
};
+/** The MediaKeys interface of EncryptedMediaExtensions API the represents a set of keys that an associated HTMLMediaElement can use for decryption of media data during playback. */
interface MediaKeys {
createSession(sessionType?: MediaKeySessionType): MediaKeySession;
- setServerCertificate(serverCertificate: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise<void>;
+ setServerCertificate(serverCertificate: BufferSource): Promise<boolean>;
}
declare var MediaKeys: {
@@ -9839,6 +10009,7 @@
"change": MediaQueryListEvent;
}
+/** A MediaQueryList object stores information on a media query applied to a document, and handles sending notifications to listeners when the media query state change (i.e. when the media query test starts or stops evaluating to true). */
interface MediaQueryList extends EventTarget {
readonly matches: boolean;
readonly media: string;
@@ -9868,14 +10039,30 @@
new(type: string, eventInitDict?: MediaQueryListEventInit): MediaQueryListEvent;
};
+interface MediaSourceEventMap {
+ "sourceclose": Event;
+ "sourceended": Event;
+ "sourceopen": Event;
+}
+
+/** The MediaSource interface of the Media Source Extensions API represents a source of media data for an HTMLMediaElement object. A MediaSource object can be attached to a HTMLMediaElement to be played in the user agent. */
interface MediaSource extends EventTarget {
readonly activeSourceBuffers: SourceBufferList;
duration: number;
+ onsourceclose: ((this: MediaSource, ev: Event) => any) | null;
+ onsourceended: ((this: MediaSource, ev: Event) => any) | null;
+ onsourceopen: ((this: MediaSource, ev: Event) => any) | null;
readonly readyState: ReadyState;
readonly sourceBuffers: SourceBufferList;
addSourceBuffer(type: string): SourceBuffer;
+ clearLiveSeekableRange(): void;
endOfStream(error?: EndOfStreamError): void;
removeSourceBuffer(sourceBuffer: SourceBuffer): void;
+ setLiveSeekableRange(start: number, end: number): void;
+ addEventListener<K extends keyof MediaSourceEventMap>(type: K, listener: (this: MediaSource, ev: MediaSourceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
+ removeEventListener<K extends keyof MediaSourceEventMap>(type: K, listener: (this: MediaSource, ev: MediaSourceEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}
declare var MediaSource: {
@@ -9891,6 +10078,7 @@
"removetrack": MediaStreamTrackEvent;
}
+/** The MediaStream interface represents a stream of media content. A stream consists of several tracks such as video or audio tracks. Each track is specified as an instance of MediaStreamTrack. */
interface MediaStream extends EventTarget {
readonly active: boolean;
readonly id: string;
@@ -9928,6 +10116,7 @@
new(context: AudioContext, options?: AudioNodeOptions): MediaStreamAudioDestinationNode;
};
+/** A MediaStreamAudioSourceNode has no inputs and exactly one output, and is created using the AudioContext.createMediaStreamSource method. The number of channels in the output equals the number of channels in AudioMediaStreamTrack. If there is no valid media stream, then the number of output channels will be one silent channel. */
interface MediaStreamAudioSourceNode extends AudioNode {
readonly mediaStream: MediaStream;
}
@@ -9957,6 +10146,7 @@
new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent;
};
+/** The MediaStreamEvent interface represents events that occurs in relation to a MediaStream. Two events of this type can be thrown: addstream and removestream. */
interface MediaStreamEvent extends Event {
readonly stream: MediaStream | null;
}
@@ -9974,6 +10164,7 @@
"unmute": Event;
}
+/** The MediaStreamTrack interface represents a single media track within a stream; typically, these are audio or video tracks, but other track types may exist as well. */
interface MediaStreamTrack extends EventTarget {
enabled: boolean;
readonly id: string;
@@ -10014,6 +10205,7 @@
new(context: AudioContext, options: MediaStreamTrackAudioSourceOptions): MediaStreamTrackAudioSourceNode;
};
+/** The MediaStreamTrackEvent interface represents events which indicate that a MediaStream has had tracks added to or removed from the stream through calls to Media Stream API methods. These events are sent to the stream when these changes occur. */
interface MediaStreamTrackEvent extends Event {
readonly track: MediaStreamTrack;
}
@@ -10023,6 +10215,7 @@
new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent;
};
+/** The MessageChannel interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. */
interface MessageChannel {
readonly port1: MessagePort;
readonly port2: MessagePort;
@@ -10033,6 +10226,7 @@
new(): MessageChannel;
};
+/** The MessageEvent interface represents a message received by a target object. */
interface MessageEvent extends Event {
/**
* Returns the data of the message.
@@ -10071,6 +10265,7 @@
"messageerror": MessageEvent;
}
+/** The MessagePort interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. */
interface MessagePort extends EventTarget {
onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null;
onmessageerror: ((this: MessagePort, ev: MessageEvent) => any) | null;
@@ -10101,6 +10296,7 @@
new(): MessagePort;
};
+/** The MimeType interface provides contains information about a MIME type associated with a particular plugin. NavigatorPlugins.mimeTypes returns an array of this object. */
interface MimeType {
readonly description: string;
readonly enabledPlugin: Plugin;
@@ -10113,6 +10309,7 @@
new(): MimeType;
};
+/** The MimeTypeArray interface returns an array of MimeType instances, each of which contains information about a supported browser plugins. This object is returned by NavigatorPlugins.mimeTypes. */
interface MimeTypeArray {
readonly length: number;
item(index: number): Plugin;
@@ -10125,6 +10322,7 @@
new(): MimeTypeArray;
};
+/** The MouseEvent interface represents events that occur due to the user interacting with a pointing device (such as a mouse). Common events using this interface include click, dblclick, mouseup, mousedown. */
interface MouseEvent extends UIEvent {
readonly altKey: boolean;
readonly button: number;
@@ -10162,6 +10360,7 @@
new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent;
};
+/** Provides event properties that are specific to modifications to the Document Object Model (DOM) hierarchy and nodes. */
interface MutationEvent extends Event {
readonly attrChange: number;
readonly attrName: string;
@@ -10182,6 +10381,7 @@
readonly REMOVAL: number;
};
+/** The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature which was part of the DOM3 Events specification. */
interface MutationObserver {
disconnect(): void;
/**
@@ -10226,6 +10426,7 @@
new(callback: MutationCallback): MutationObserver;
};
+/** A MutationRecord represents an individual DOM mutation. It is the object that is passed to MutationObserver's callback. */
interface MutationRecord {
readonly addedNodes: NodeList;
/**
@@ -10271,6 +10472,7 @@
new(): MutationRecord;
};
+/** The NamedNodeMap interface represents a collection of Attr objects. Objects inside a NamedNodeMap are not in any particular order, unlike NodeList, although they may be accessed by an index as in an array. */
interface NamedNodeMap {
readonly length: number;
getNamedItem(qualifiedName: string): Attr | null;
@@ -10300,9 +10502,11 @@
new(): NavigationPreloadManager;
};
+/** The Navigator interface represents the state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities. */
interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia, NavigatorLanguage, NavigatorStorage, NavigatorAutomationInformation {
readonly activeVRDisplays: ReadonlyArray<VRDisplay>;
readonly authentication: WebAuthentication;
+ readonly clipboard: Clipboard;
readonly cookieEnabled: boolean;
readonly doNotTrack: string | null;
gamepadInputEmulation: GamepadInputEmulationType;
@@ -10378,6 +10582,7 @@
getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void;
}
+/** Node is an interface from which a number of DOM API object types inherit. It allows those types to be treated similarly; for example, inheriting the same set of methods, or being tested in the same way. */
interface Node extends EventTarget {
/**
* Returns node's node document's document base URL.
@@ -10404,7 +10609,7 @@
/**
* Returns the next sibling.
*/
- readonly nextSibling: Node | null;
+ readonly nextSibling: ChildNode | null;
/**
* Returns a string appropriate for the type of node, as
* follows:
@@ -10524,6 +10729,7 @@
readonly TEXT_NODE: number;
};
+/** A NodeFilter interface represents an object used to filter the nodes in a NodeIterator or TreeWalker. They don't know anything about the DOM or how to traverse nodes; they just know how to evaluate a single node against the provided filter. */
interface NodeFilter {
acceptNode(node: Node): number;
}
@@ -10547,6 +10753,7 @@
readonly SHOW_TEXT: number;
};
+/** The NodeIterator interface represents an iterator over the members of a list of the nodes in a subtree of the DOM. The nodes will be returned in document order. */
interface NodeIterator {
readonly filter: NodeFilter | null;
readonly pointerBeforeReferenceNode: boolean;
@@ -10563,6 +10770,7 @@
new(): NodeIterator;
};
+/** NodeList objects are collections of nodes, usually returned by properties such as Node.childNodes and methods such as document.querySelectorAll(). */
interface NodeList {
/**
* Returns the number of nodes in the collection.
@@ -10634,6 +10842,7 @@
"show": Event;
}
+/** The Notification interface of the Notifications API is used to configure and display desktop notifications to the user. */
interface Notification extends EventTarget {
readonly actions: ReadonlyArray<NotificationAction>;
readonly badge: string;
@@ -10669,23 +10878,29 @@
requestPermission(deprecatedCallback?: NotificationPermissionCallback): Promise<NotificationPermission>;
};
+/** The OES_element_index_uint extension is part of the WebGL API and adds support for gl.UNSIGNED_INT types to WebGLRenderingContext.drawElements(). */
interface OES_element_index_uint {
}
+/** The OES_standard_derivatives extension is part of the WebGL API and adds the GLSL derivative functions dFdx, dFdy, and fwidth. */
interface OES_standard_derivatives {
readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: GLenum;
}
+/** The OES_texture_float extension is part of the WebGL API and exposes floating-point pixel types for textures. */
interface OES_texture_float {
}
+/** The OES_texture_float_linear extension is part of the WebGL API and allows linear filtering with floating-point pixel types for textures. */
interface OES_texture_float_linear {
}
+/** The OES_texture_half_float extension is part of the WebGL API and adds texture formats with 16- (aka half float) and 32-bit floating-point components. */
interface OES_texture_half_float {
readonly HALF_FLOAT_OES: GLenum;
}
+/** The OES_texture_half_float_linear extension is part of the WebGL API and allows linear filtering with half floating-point pixel types for textures. */
interface OES_texture_half_float_linear {
}
@@ -10697,6 +10912,7 @@
readonly VERTEX_ARRAY_BINDING_OES: GLenum;
}
+/** The Web Audio API OfflineAudioCompletionEvent interface represents events that occur when the processing of an OfflineAudioContext is terminated. The complete event implements this interface. */
interface OfflineAudioCompletionEvent extends Event {
readonly renderedBuffer: AudioBuffer;
}
@@ -10710,6 +10926,7 @@
"complete": OfflineAudioCompletionEvent;
}
+/** The OfflineAudioContext interface is an AudioContext interface representing an audio-processing graph built from linked together AudioNodes. In contrast with a standard AudioContext, an OfflineAudioContext doesn't render the audio to the device hardware; instead, it generates it, as fast as it can, and outputs the result to an AudioBuffer. */
interface OfflineAudioContext extends BaseAudioContext {
readonly length: number;
oncomplete: ((this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any) | null;
@@ -10727,6 +10944,7 @@
new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext;
};
+/** The OscillatorNode interface represents a periodic waveform, such as a sine wave. It is an AudioScheduledSourceNode audio-processing module that causes a specified frequency of a given wave to be created—in effect, a constant tone. */
interface OscillatorNode extends AudioScheduledSourceNode {
readonly detune: AudioParam;
readonly frequency: AudioParam;
@@ -10760,6 +10978,7 @@
readonly VERTICAL: number;
};
+/** The PageTransitionEvent is fired when a document is being loaded or unloaded. */
interface PageTransitionEvent extends Event {
readonly persisted: boolean;
}
@@ -10769,6 +10988,7 @@
new(): PageTransitionEvent;
};
+/** A PannerNode always has exactly one input and one output: the input can be mono or stereo but the output is always stereo (2 channels); you can't have panning effects without at least two audio channels! */
interface PannerNode extends AudioNode {
coneInnerAngle: number;
coneOuterAngle: number;
@@ -10839,6 +11059,7 @@
querySelectorAll<E extends Element = Element>(selectors: string): NodeListOf<E>;
}
+/** The Path2D interface of the Canvas 2D API is used to declare a path that can then be used on a CanvasRenderingContext2D object. The path methods of the CanvasRenderingContext2D interface are also present on this interface, which gives you the convenience of being able to retain and replay your path whenever desired. */
interface Path2D extends CanvasPath {
addPath(path: Path2D, transform?: DOMMatrix2DInit): void;
}
@@ -10848,6 +11069,7 @@
new(path?: Path2D | string): Path2D;
};
+/** The PaymentAddress interface of the Payment Request API is used to store shipping or payment address information. */
interface PaymentAddress {
readonly addressLine: string[];
readonly city: string;
@@ -10873,6 +11095,7 @@
"shippingoptionchange": Event;
}
+/** The PaymentRequest interface of the Payment Request API is the primary access point into the API, and lets web content and apps accept payments from the end user. */
interface PaymentRequest extends EventTarget {
readonly id: string;
onshippingaddresschange: ((this: PaymentRequest, ev: Event) => any) | null;
@@ -10894,8 +11117,9 @@
new(methodData: PaymentMethodData[], details: PaymentDetailsInit, options?: PaymentOptions): PaymentRequest;
};
+/** The PaymentRequestUpdateEvent interface of the the Payment Request API enables a web page to update the details of a PaymentRequest in response to a user action. */
interface PaymentRequestUpdateEvent extends Event {
- updateWith(detailsPromise: Promise<PaymentDetailsUpdate>): void;
+ updateWith(detailsPromise: PaymentDetailsUpdate | Promise<PaymentDetailsUpdate>): void;
}
declare var PaymentRequestUpdateEvent: {
@@ -10903,6 +11127,7 @@
new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent;
};
+/** The PaymentResponse interface of the Payment Request API is returned after a user selects a payment method and approves a payment request. */
interface PaymentResponse {
readonly details: any;
readonly methodName: string;
@@ -10954,6 +11179,7 @@
"resourcetimingbufferfull": Event;
}
+/** The Performance interface provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */
interface Performance extends EventTarget {
/** @deprecated */
readonly navigation: PerformanceNavigation;
@@ -10983,6 +11209,7 @@
new(): Performance;
};
+/** The PerformanceEntry object encapsulates a single performance metric that is part of the performance timeline. A performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application. Performance entries are also created in indirect ways such as loading a resource (such as an image). */
interface PerformanceEntry {
readonly duration: number;
readonly entryType: string;
@@ -10996,6 +11223,7 @@
new(): PerformanceEntry;
};
+/** PerformanceMark is an abstract interface for PerformanceEntry objects with an entryType of "mark". Entries of this type are created by calling performance.mark() to add a named DOMHighResTimeStamp (the mark) to the browser's performance timeline. */
interface PerformanceMark extends PerformanceEntry {
}
@@ -11004,6 +11232,7 @@
new(): PerformanceMark;
};
+/** PerformanceMeasure is an abstract interface for PerformanceEntry objects with an entryType of "measure". Entries of this type are created by calling performance.measure() to add a named DOMHighResTimeStamp (the measure) between two marks to the browser's performance timeline. */
interface PerformanceMeasure extends PerformanceEntry {
}
@@ -11012,6 +11241,7 @@
new(): PerformanceMeasure;
};
+/** The legacy PerformanceNavigation interface represents information about how the navigation to the current document was done. */
interface PerformanceNavigation {
readonly redirectCount: number;
readonly type: number;
@@ -11031,6 +11261,7 @@
readonly TYPE_RESERVED: number;
};
+/** The PerformanceNavigationTiming interface provides methods and properties to store and retrieve metrics regarding the browser's document navigation events. For example, this interface can be used to determine how much time it takes to load or unload a document. */
interface PerformanceNavigationTiming extends PerformanceResourceTiming {
readonly domComplete: number;
readonly domContentLoadedEventEnd: number;
@@ -11072,6 +11303,7 @@
new(): PerformanceObserverEntryList;
};
+/** The PerformanceResourceTiming interface enables retrieval and analysis of detailed network timing data regarding the loading of an application's resources. An application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource, such as an XMLHttpRequest, <SVG>, image, or script. */
interface PerformanceResourceTiming extends PerformanceEntry {
readonly connectEnd: number;
readonly connectStart: number;
@@ -11098,6 +11330,7 @@
new(): PerformanceResourceTiming;
};
+/** The PerformanceTiming interface is a legacy interface kept for backwards compatibility and contains properties that offer performance timing information for various events which occur during the loading and use of the current page. You get a PerformanceTiming object describing your page using the window.performance.timing property. */
interface PerformanceTiming {
readonly connectEnd: number;
readonly connectStart: number;
@@ -11128,6 +11361,7 @@
new(): PerformanceTiming;
};
+/** PeriodicWave has no inputs or outputs; it is used to define custom oscillators when calling OscillatorNode.setPeriodicWave(). The PeriodicWave itself is created/returned by AudioContext.createPeriodicWave(). */
interface PeriodicWave {
}
@@ -11155,6 +11389,7 @@
new(): PermissionRequestedEvent;
};
+/** The Plugin interface provides information about a browser plugin. */
interface Plugin {
readonly description: string;
readonly filename: string;
@@ -11171,6 +11406,7 @@
new(): Plugin;
};
+/** The PluginArray interface is used to store a list of Plugin objects describing the available plugins; it's returned by the window.navigator.plugins property. The PluginArray is not a JavaScript array, but has the length property and supports accessing individual items using bracket notation (plugins[2]), as well as via item(index) and namedItem("name") methods. */
interface PluginArray {
readonly length: number;
item(index: number): Plugin;
@@ -11184,6 +11420,7 @@
new(): PluginArray;
};
+/** The PointerEvent interface represents the state of a DOM event produced by a pointer such as the geometry of the contact point, the device type that generated the event, the amount of pressure that was applied on the contact surface, etc. */
interface PointerEvent extends MouseEvent {
readonly height: number;
readonly isPrimary: boolean;
@@ -11202,6 +11439,7 @@
new(type: string, eventInitDict?: PointerEventInit): PointerEvent;
};
+/** An event handler for the popstate event on the window. */
interface PopStateEvent extends Event {
readonly state: any;
}
@@ -11211,11 +11449,13 @@
new(type: string, eventInitDict?: PopStateEventInit): PopStateEvent;
};
+/** The Position interface represents the position of the concerned device at a given time. The position, represented by a Coordinates object, comprehends the 2D position of the device, on a spheroid representing the Earth, but also its altitude and its speed. */
interface Position {
readonly coords: Coordinates;
readonly timestamp: number;
}
+/** The PositionError interface represents the reason of an error occurring when using the geolocating device. */
interface PositionError {
readonly code: number;
readonly message: string;
@@ -11224,6 +11464,7 @@
readonly TIMEOUT: number;
}
+/** A processing instruction embeds application-specific instructions in XML which can be ignored by other applications that don't recognize them. */
interface ProcessingInstruction extends CharacterData {
readonly target: string;
}
@@ -11233,6 +11474,7 @@
new(): ProcessingInstruction;
};
+/** The ProgressEvent interface represents events measuring progress of an underlying process, like an HTTP request (for an XMLHttpRequest, or the loading of the underlying resource of an <img>, <audio>, <video>, <style> or <link>). */
interface ProgressEvent extends Event {
readonly lengthComputable: boolean;
readonly loaded: number;
@@ -11254,6 +11496,7 @@
new(type: string, eventInitDict: PromiseRejectionEventInit): PromiseRejectionEvent;
};
+/** The PushManager interface of the Push API provides a way to receive notifications from third-party servers as well as request URLs for push notifications. */
interface PushManager {
getSubscription(): Promise<PushSubscription | null>;
permissionState(options?: PushSubscriptionOptionsInit): Promise<PushPermissionState>;
@@ -11266,6 +11509,7 @@
readonly supportedContentEncodings: ReadonlyArray<string>;
};
+/** The PushSubscription interface of the Push API provides a subcription's URL endpoint and allows unsubscription from a push service. */
interface PushSubscription {
readonly endpoint: string;
readonly expirationTime: number | null;
@@ -11321,6 +11565,7 @@
new(): RTCDTMFSender;
};
+/** The RTCDTMFToneChangeEvent interface represents events sent to indicate that DTMF tones have started or finished playing. This interface is used by the tonechange event. */
interface RTCDTMFToneChangeEvent extends Event {
readonly tone: string;
}
@@ -11460,6 +11705,7 @@
new(type: string, eventInitDict: RTCErrorEventInit): RTCErrorEvent;
};
+/** The RTCIceCandidate interface—part of the WebRTC API—represents a candidate Internet Connectivity Establishment (ICE) configuration which may be used to establish an RTCPeerConnection. */
interface RTCIceCandidate {
readonly candidate: string;
readonly component: RTCIceComponent | null;
@@ -11530,6 +11776,7 @@
"statechange": Event;
}
+/** The RTCIceTransport interface provides access to information about the ICE transport layer over which the data is being sent and received. */
interface RTCIceTransport extends EventTarget {
readonly component: RTCIceComponent;
readonly gatheringState: RTCIceGathererState;
@@ -11586,6 +11833,7 @@
"track": RTCTrackEvent;
}
+/** The RTCPeerConnection interface represents a WebRTC connection between the local computer and a remote peer. It provides methods to connect to a remote peer, maintain and monitor the connection, and close the connection once it's no longer needed. */
interface RTCPeerConnection extends EventTarget {
readonly canTrickleIceCandidates: boolean | null;
readonly connectionState: RTCPeerConnectionState;
@@ -11655,6 +11903,7 @@
new(type: string, eventInitDict: RTCPeerConnectionIceErrorEventInit): RTCPeerConnectionIceErrorEvent;
};
+/** The RTCPeerConnectionIceEvent interface represents events that occurs in relation to ICE candidates with the target, usually an RTCPeerConnection. Only one event is of this type: icecandidate. */
interface RTCPeerConnectionIceEvent extends Event {
readonly candidate: RTCIceCandidate | null;
readonly url: string | null;
@@ -11665,6 +11914,7 @@
new(type: string, eventInitDict?: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent;
};
+/** The RTCRtpReceiver interface of the the WebRTC API manages the reception and decoding of data for a MediaStreamTrack on an RTCPeerConnection. */
interface RTCRtpReceiver {
readonly rtcpTransport: RTCDtlsTransport | null;
readonly track: MediaStreamTrack;
@@ -11681,6 +11931,7 @@
getCapabilities(kind: string): RTCRtpCapabilities | null;
};
+/** The RTCRtpSender interface provides the ability to control and obtain details about how a particular MediaStreamTrack is encoded and sent to a remote peer. */
interface RTCRtpSender {
readonly dtmf: RTCDTMFSender | null;
readonly rtcpTransport: RTCDtlsTransport | null;
@@ -11736,6 +11987,7 @@
new(): RTCSctpTransport;
};
+/** The RTCSessionDescription interface describes one end of a connection—or potential connection—and how it's configured. Each RTCSessionDescription consists of a description type indicating which part of the offer/answer negotiation process it describes and of the SDP descriptor of the session. */
interface RTCSessionDescription {
readonly sdp: string;
readonly type: RTCSdpType;
@@ -11833,6 +12085,7 @@
new(): RandomSource;
};
+/** The Range interface represents a fragment of a document that can contain nodes and parts of text nodes. */
interface Range extends AbstractRange {
/**
* Returns the node, furthest away from
@@ -11892,6 +12145,7 @@
error(error?: any): void;
}
+/** The ReadableStream interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. */
interface ReadableStream<R = any> {
readonly locked: boolean;
cancel(reason?: any): Promise<void>;
@@ -11956,6 +12210,7 @@
new(): ReadableStreamReader;
};
+/** The Request interface of the Fetch API represents a resource request. */
interface Request extends Body {
/**
* Returns the cache mode associated with request, which is a string indicating
@@ -12041,6 +12296,7 @@
new(input: RequestInfo, init?: RequestInit): Request;
};
+/** The Response interface of the Fetch API represents the response to a request. */
interface Response extends Body {
readonly headers: Headers;
readonly ok: boolean;
@@ -12060,6 +12316,7 @@
redirect(url: string, status?: number): Response;
};
+/** The SVGAElement interface provides access to the properties of <a> element, as well as methods to manipulate them. */
interface SVGAElement extends SVGGraphicsElement, SVGURIReference {
readonly target: SVGAnimatedString;
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
@@ -12073,6 +12330,7 @@
new(): SVGAElement;
};
+/** The SVGAngle interface is used to represent a value that can be an <angle> or <number> value. An SVGAngle reflected through the animVal attribute is always read only. */
interface SVGAngle {
readonly unitType: number;
value: number;
@@ -12133,6 +12391,7 @@
new(): SVGAnimateTransformElement;
};
+/** The SVGAnimatedAngle interface is used for attributes of basic type <angle> which can be animated. */
interface SVGAnimatedAngle {
readonly animVal: SVGAngle;
readonly baseVal: SVGAngle;
@@ -12143,6 +12402,7 @@
new(): SVGAnimatedAngle;
};
+/** The SVGAnimatedBoolean interface is used for attributes of type boolean which can be animated. */
interface SVGAnimatedBoolean {
readonly animVal: boolean;
baseVal: boolean;
@@ -12153,6 +12413,7 @@
new(): SVGAnimatedBoolean;
};
+/** The SVGAnimatedEnumeration interface is used for attributes whose value must be a constant from a particular enumeration and which can be animated. */
interface SVGAnimatedEnumeration {
readonly animVal: number;
baseVal: number;
@@ -12163,6 +12424,7 @@
new(): SVGAnimatedEnumeration;
};
+/** The SVGAnimatedInteger interface is used for attributes of basic type <integer> which can be animated. */
interface SVGAnimatedInteger {
readonly animVal: number;
baseVal: number;
@@ -12173,6 +12435,7 @@
new(): SVGAnimatedInteger;
};
+/** The SVGAnimatedLength interface is used for attributes of basic type <length> which can be animated. */
interface SVGAnimatedLength {
readonly animVal: SVGLength;
readonly baseVal: SVGLength;
@@ -12183,6 +12446,7 @@
new(): SVGAnimatedLength;
};
+/** The SVGAnimatedLengthList interface is used for attributes of type SVGLengthList which can be animated. */
interface SVGAnimatedLengthList {
readonly animVal: SVGLengthList;
readonly baseVal: SVGLengthList;
@@ -12193,6 +12457,7 @@
new(): SVGAnimatedLengthList;
};
+/** The SVGAnimatedNumber interface is used for attributes of basic type <Number> which can be animated. */
interface SVGAnimatedNumber {
readonly animVal: number;
baseVal: number;
@@ -12203,6 +12468,7 @@
new(): SVGAnimatedNumber;
};
+/** The SVGAnimatedNumber interface is used for attributes which take a list of numbers and which can be animated. */
interface SVGAnimatedNumberList {
readonly animVal: SVGNumberList;
readonly baseVal: SVGNumberList;
@@ -12218,6 +12484,7 @@
readonly points: SVGPointList;
}
+/** The SVGAnimatedPreserveAspectRatio interface is used for attributes of type SVGPreserveAspectRatio which can be animated. */
interface SVGAnimatedPreserveAspectRatio {
readonly animVal: SVGPreserveAspectRatio;
readonly baseVal: SVGPreserveAspectRatio;
@@ -12228,6 +12495,7 @@
new(): SVGAnimatedPreserveAspectRatio;
};
+/** The SVGAnimatedRect interface is used for attributes of basic SVGRect which can be animated. */
interface SVGAnimatedRect {
readonly animVal: DOMRectReadOnly;
readonly baseVal: DOMRect;
@@ -12238,6 +12506,7 @@
new(): SVGAnimatedRect;
};
+/** The SVGAnimatedString interface represents string attributes which can be animated from each SVG declaration. You need to create SVG attribute before doing anything else, everything should be declared inside this. */
interface SVGAnimatedString {
readonly animVal: string;
baseVal: string;
@@ -12248,6 +12517,7 @@
new(): SVGAnimatedString;
};
+/** The SVGAnimatedTransformList interface is used for attributes which take a list of numbers and which can be animated. */
interface SVGAnimatedTransformList {
readonly animVal: SVGTransformList;
readonly baseVal: SVGTransformList;
@@ -12274,6 +12544,7 @@
new(): SVGAnimationElement;
};
+/** The SVGCircleElement interface is an interface for the <circle> element. The circle element is defined by the cx and cy attributes that denote the coordinates of the centre of the circle. */
interface SVGCircleElement extends SVGGraphicsElement {
readonly cx: SVGAnimatedLength;
readonly cy: SVGAnimatedLength;
@@ -12289,6 +12560,7 @@
new(): SVGCircleElement;
};
+/** The SVGClipPathElement interface provides access to the properties of <clipPath> elements, as well as methods to manipulate them. */
interface SVGClipPathElement extends SVGGraphicsElement {
readonly clipPathUnits: SVGAnimatedEnumeration;
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
@@ -12302,6 +12574,7 @@
new(): SVGClipPathElement;
};
+/** The SVGComponentTransferFunctionElement interface defines a base interface used by the component transfer function interfaces. */
interface SVGComponentTransferFunctionElement extends SVGElement {
readonly amplitude: SVGAnimatedNumber;
readonly exponent: SVGAnimatedNumber;
@@ -12347,6 +12620,7 @@
new(): SVGCursorElement;
};
+/** The SVGDefsElement interface corresponds to the <defs> element. */
interface SVGDefsElement extends SVGGraphicsElement {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -12359,6 +12633,7 @@
new(): SVGDefsElement;
};
+/** The SVGDescElement interface corresponds to the <desc> element. */
interface SVGDescElement extends SVGElement {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -12374,6 +12649,7 @@
interface SVGElementEventMap extends ElementEventMap, GlobalEventHandlersEventMap, DocumentAndElementEventHandlersEventMap {
}
+/** All of the SVG DOM interfaces that correspond directly to elements in the SVG language derive from the SVGElement interface. */
interface SVGElement extends Element, GlobalEventHandlers, DocumentAndElementEventHandlers, SVGElementInstance, HTMLOrSVGElement, ElementCSSInlineStyle {
/** @deprecated */
readonly className: any;
@@ -12412,6 +12688,7 @@
new(): SVGElementInstanceList;
};
+/** The SVGEllipseElement interface provides access to the properties of <ellipse> elements. */
interface SVGEllipseElement extends SVGGraphicsElement {
readonly cx: SVGAnimatedLength;
readonly cy: SVGAnimatedLength;
@@ -12428,6 +12705,7 @@
new(): SVGEllipseElement;
};
+/** The SVGFEBlendElement interface corresponds to the <feBlend> element. */
interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {
readonly in1: SVGAnimatedString;
readonly in2: SVGAnimatedString;
@@ -12477,6 +12755,7 @@
readonly SVG_FEBLEND_MODE_UNKNOWN: number;
};
+/** The SVGFEColorMatrixElement interface corresponds to the <feColorMatrix> element. */
interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {
readonly in1: SVGAnimatedString;
readonly type: SVGAnimatedEnumeration;
@@ -12502,6 +12781,7 @@
readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number;
};
+/** The SVGFEComponentTransferElement interface corresponds to the <feComponentTransfer> element. */
interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {
readonly in1: SVGAnimatedString;
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
@@ -12515,6 +12795,7 @@
new(): SVGFEComponentTransferElement;
};
+/** The SVGFECompositeElement interface corresponds to the <feComposite> element. */
interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {
readonly in1: SVGAnimatedString;
readonly in2: SVGAnimatedString;
@@ -12548,6 +12829,7 @@
readonly SVG_FECOMPOSITE_OPERATOR_XOR: number;
};
+/** The SVGFEConvolveMatrixElement interface corresponds to the <feConvolveMatrix> element. */
interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {
readonly bias: SVGAnimatedNumber;
readonly divisor: SVGAnimatedNumber;
@@ -12580,6 +12862,7 @@
readonly SVG_EDGEMODE_WRAP: number;
};
+/** The SVGFEDiffuseLightingElement interface corresponds to the <feDiffuseLighting> element. */
interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {
readonly diffuseConstant: SVGAnimatedNumber;
readonly in1: SVGAnimatedString;
@@ -12597,6 +12880,7 @@
new(): SVGFEDiffuseLightingElement;
};
+/** The SVGFEDisplacementMapElement interface corresponds to the <feDisplacementMap> element. */
interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {
readonly in1: SVGAnimatedString;
readonly in2: SVGAnimatedString;
@@ -12624,6 +12908,7 @@
readonly SVG_CHANNEL_UNKNOWN: number;
};
+/** The SVGFEDistantLightElement interface corresponds to the <feDistantLight> element. */
interface SVGFEDistantLightElement extends SVGElement {
readonly azimuth: SVGAnimatedNumber;
readonly elevation: SVGAnimatedNumber;
@@ -12638,6 +12923,7 @@
new(): SVGFEDistantLightElement;
};
+/** The SVGFEFloodElement interface corresponds to the <feFlood> element. */
interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -12650,6 +12936,7 @@
new(): SVGFEFloodElement;
};
+/** The SVGFEFuncAElement interface corresponds to the <feFuncA> element. */
interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -12662,6 +12949,7 @@
new(): SVGFEFuncAElement;
};
+/** The SVGFEFuncBElement interface corresponds to the <feFuncB> element. */
interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -12674,6 +12962,7 @@
new(): SVGFEFuncBElement;
};
+/** The SVGFEFuncGElement interface corresponds to the <feFuncG> element. */
interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -12686,6 +12975,7 @@
new(): SVGFEFuncGElement;
};
+/** The SVGFEFuncRElement interface corresponds to the <feFuncR> element. */
interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -12698,6 +12988,7 @@
new(): SVGFEFuncRElement;
};
+/** The SVGFEGaussianBlurElement interface corresponds to the <feGaussianBlur> element. */
interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {
readonly in1: SVGAnimatedString;
readonly stdDeviationX: SVGAnimatedNumber;
@@ -12714,6 +13005,7 @@
new(): SVGFEGaussianBlurElement;
};
+/** The SVGFEImageElement interface corresponds to the <feImage> element. */
interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference {
readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio;
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
@@ -12727,6 +13019,7 @@
new(): SVGFEImageElement;
};
+/** The SVGFEMergeElement interface corresponds to the <feMerge> element. */
interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -12739,6 +13032,7 @@
new(): SVGFEMergeElement;
};
+/** The SVGFEMergeNodeElement interface corresponds to the <feMergeNode> element. */
interface SVGFEMergeNodeElement extends SVGElement {
readonly in1: SVGAnimatedString;
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
@@ -12752,6 +13046,7 @@
new(): SVGFEMergeNodeElement;
};
+/** The SVGFEMorphologyElement interface corresponds to the <feMorphology> element. */
interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {
readonly in1: SVGAnimatedString;
readonly operator: SVGAnimatedEnumeration;
@@ -12774,6 +13069,7 @@
readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number;
};
+/** The SVGFEOffsetElement interface corresponds to the <feOffset> element. */
interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {
readonly dx: SVGAnimatedNumber;
readonly dy: SVGAnimatedNumber;
@@ -12789,6 +13085,7 @@
new(): SVGFEOffsetElement;
};
+/** The SVGFEPointLightElement interface corresponds to the <fePointLight> element. */
interface SVGFEPointLightElement extends SVGElement {
readonly x: SVGAnimatedNumber;
readonly y: SVGAnimatedNumber;
@@ -12804,6 +13101,7 @@
new(): SVGFEPointLightElement;
};
+/** The SVGFESpecularLightingElement interface corresponds to the <feSpecularLighting> element. */
interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {
readonly in1: SVGAnimatedString;
readonly kernelUnitLengthX: SVGAnimatedNumber;
@@ -12822,6 +13120,7 @@
new(): SVGFESpecularLightingElement;
};
+/** The SVGFESpotLightElement interface corresponds to the <feSpotLight> element. */
interface SVGFESpotLightElement extends SVGElement {
readonly limitingConeAngle: SVGAnimatedNumber;
readonly pointsAtX: SVGAnimatedNumber;
@@ -12842,6 +13141,7 @@
new(): SVGFESpotLightElement;
};
+/** The SVGFETileElement interface corresponds to the <feTile> element. */
interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {
readonly in1: SVGAnimatedString;
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
@@ -12855,6 +13155,7 @@
new(): SVGFETileElement;
};
+/** The SVGFETurbulenceElement interface corresponds to the <feTurbulence> element. */
interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {
readonly baseFrequencyX: SVGAnimatedNumber;
readonly baseFrequencyY: SVGAnimatedNumber;
@@ -12885,6 +13186,7 @@
readonly SVG_TURBULENCE_TYPE_UNKNOWN: number;
};
+/** The SVGFilterElement interface provides access to the properties of <filter> elements, as well as methods to manipulate them. */
interface SVGFilterElement extends SVGElement, SVGURIReference {
/** @deprecated */
readonly filterResX: SVGAnimatedInteger;
@@ -12922,6 +13224,7 @@
readonly viewBox: SVGAnimatedRect;
}
+/** The SVGForeignObjectElement interface provides access to the properties of <foreignObject> elements, as well as methods to manipulate them. */
interface SVGForeignObjectElement extends SVGGraphicsElement {
readonly height: SVGAnimatedLength;
readonly width: SVGAnimatedLength;
@@ -12938,6 +13241,7 @@
new(): SVGForeignObjectElement;
};
+/** The SVGGElement interface corresponds to the <g> element. */
interface SVGGElement extends SVGGraphicsElement {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -12967,6 +13271,7 @@
new(): SVGGeometryElement;
};
+/** The SVGGradient interface is a base interface used by SVGLinearGradientElement and SVGRadialGradientElement. */
interface SVGGradientElement extends SVGElement, SVGURIReference {
readonly gradientTransform: SVGAnimatedTransformList;
readonly gradientUnits: SVGAnimatedEnumeration;
@@ -12990,6 +13295,7 @@
readonly SVG_SPREADMETHOD_UNKNOWN: number;
};
+/** The SVGGraphicsElement interface represents SVG elements whose primary purpose is to directly render graphics into a group. */
interface SVGGraphicsElement extends SVGElement, SVGTests {
readonly transform: SVGAnimatedTransformList;
getBBox(options?: SVGBoundingBoxOptions): DOMRect;
@@ -13006,6 +13312,7 @@
new(): SVGGraphicsElement;
};
+/** The SVGImageElement interface corresponds to the <image> element. */
interface SVGImageElement extends SVGGraphicsElement, SVGURIReference {
readonly height: SVGAnimatedLength;
readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio;
@@ -13023,6 +13330,7 @@
new(): SVGImageElement;
};
+/** The SVGLength interface correspond to the <length> basic data type. */
interface SVGLength {
readonly unitType: number;
value: number;
@@ -13059,6 +13367,7 @@
readonly SVG_LENGTHTYPE_UNKNOWN: number;
};
+/** The SVGLengthList defines a list of SVGLength objects. */
interface SVGLengthList {
readonly length: number;
readonly numberOfItems: number;
@@ -13077,6 +13386,7 @@
new(): SVGLengthList;
};
+/** The SVGLineElement interface provides access to the properties of <line> elements, as well as methods to manipulate them. */
interface SVGLineElement extends SVGGraphicsElement {
readonly x1: SVGAnimatedLength;
readonly x2: SVGAnimatedLength;
@@ -13093,6 +13403,7 @@
new(): SVGLineElement;
};
+/** The SVGLinearGradientElement interface corresponds to the <linearGradient> element. */
interface SVGLinearGradientElement extends SVGGradientElement {
readonly x1: SVGAnimatedLength;
readonly x2: SVGAnimatedLength;
@@ -13142,6 +13453,7 @@
readonly SVG_MARKER_ORIENT_UNKNOWN: number;
};
+/** The SVGMaskElement interface provides access to the properties of <mask> elements, as well as methods to manipulate them. */
interface SVGMaskElement extends SVGElement, SVGTests {
readonly height: SVGAnimatedLength;
readonly maskContentUnits: SVGAnimatedEnumeration;
@@ -13160,6 +13472,7 @@
new(): SVGMaskElement;
};
+/** The SVGMetadataElement interface corresponds to the <metadata> element. */
interface SVGMetadataElement extends SVGElement {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -13172,6 +13485,7 @@
new(): SVGMetadataElement;
};
+/** The SVGNumber interface corresponds to the <number> basic data type. */
interface SVGNumber {
value: number;
}
@@ -13181,6 +13495,7 @@
new(): SVGNumber;
};
+/** The SVGNumberList defines a list of SVGNumber objects. */
interface SVGNumberList {
readonly length: number;
readonly numberOfItems: number;
@@ -13199,6 +13514,7 @@
new(): SVGNumberList;
};
+/** The SVGPathElement interface corresponds to the <path> element. */
interface SVGPathElement extends SVGGraphicsElement {
/** @deprecated */
readonly pathSegList: SVGPathSegList;
@@ -13531,6 +13847,7 @@
new(): SVGPathSegMovetoRel;
};
+/** The SVGPatternElement interface corresponds to the <pattern> element. */
interface SVGPatternElement extends SVGElement, SVGTests, SVGFitToViewBox, SVGURIReference {
readonly height: SVGAnimatedLength;
readonly patternContentUnits: SVGAnimatedEnumeration;
@@ -13566,6 +13883,7 @@
new(): SVGPointList;
};
+/** The SVGPolygonElement interface provides access to the properties of <polygon> elements, as well as methods to manipulate them. */
interface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -13578,6 +13896,7 @@
new(): SVGPolygonElement;
};
+/** The SVGPolylineElement interface provides access to the properties of <polyline> elements, as well as methods to manipulate them. */
interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -13590,6 +13909,7 @@
new(): SVGPolylineElement;
};
+/** The SVGPreserveAspectRatio interface corresponds to the preserveAspectRatio attribute, which is available for some of SVG's elements. */
interface SVGPreserveAspectRatio {
align: number;
meetOrSlice: number;
@@ -13628,6 +13948,7 @@
readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number;
};
+/** The SVGRadialGradientElement interface corresponds to the <RadialGradient> element. */
interface SVGRadialGradientElement extends SVGGradientElement {
readonly cx: SVGAnimatedLength;
readonly cy: SVGAnimatedLength;
@@ -13645,6 +13966,7 @@
new(): SVGRadialGradientElement;
};
+/** The SVGRectElement interface provides access to the properties of <rect> elements, as well as methods to manipulate them. */
interface SVGRectElement extends SVGGraphicsElement {
readonly height: SVGAnimatedLength;
readonly rx: SVGAnimatedLength;
@@ -13668,6 +13990,7 @@
"SVGZoom": SVGZoomEvent;
}
+/** The SVGSVGElement interface provides access to the properties of <svg> elements, as well as methods to manipulate them. This interface contains also various miscellaneous commonly-used utility methods, such as matrix operations and the ability to control the time of redraw on visual rendering devices. */
interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan {
/** @deprecated */
contentScriptType: string;
@@ -13736,6 +14059,7 @@
readonly SVG_ZOOMANDPAN_UNKNOWN: number;
};
+/** The SVGScriptElement interface corresponds to the SVG <script> element. */
interface SVGScriptElement extends SVGElement, SVGURIReference {
type: string;
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
@@ -13749,6 +14073,7 @@
new(): SVGScriptElement;
};
+/** The SVGStopElement interface corresponds to the <stop> element. */
interface SVGStopElement extends SVGElement {
readonly offset: SVGAnimatedNumber;
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
@@ -13762,6 +14087,7 @@
new(): SVGStopElement;
};
+/** The SVGStringList defines a list of DOMString objects. */
interface SVGStringList {
readonly length: number;
readonly numberOfItems: number;
@@ -13780,6 +14106,7 @@
new(): SVGStringList;
};
+/** The SVGStyleElement interface corresponds to the SVG <style> element. */
interface SVGStyleElement extends SVGElement {
disabled: boolean;
media: string;
@@ -13796,6 +14123,7 @@
new(): SVGStyleElement;
};
+/** The SVGSwitchElement interface corresponds to the <switch> element. */
interface SVGSwitchElement extends SVGGraphicsElement {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -13808,6 +14136,7 @@
new(): SVGSwitchElement;
};
+/** The SVGSymbolElement interface corresponds to the <symbol> element. */
interface SVGSymbolElement extends SVGElement, SVGFitToViewBox {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -13820,6 +14149,7 @@
new(): SVGSymbolElement;
};
+/** The SVGTSpanElement interface represents a <tspan> element. */
interface SVGTSpanElement extends SVGTextPositioningElement {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -13837,6 +14167,7 @@
readonly systemLanguage: SVGStringList;
}
+/** The SVGTextContentElement interface is implemented by elements that support rendering child text content. It is inherited by various text-related interfaces, such as SVGTextElement, SVGTSpanElement, SVGTRefElement, SVGAltGlyphElement and SVGTextPathElement. */
interface SVGTextContentElement extends SVGGraphicsElement {
readonly lengthAdjust: SVGAnimatedEnumeration;
readonly textLength: SVGAnimatedLength;
@@ -13866,6 +14197,7 @@
readonly LENGTHADJUST_UNKNOWN: number;
};
+/** The SVGTextElement interface corresponds to the <text> elements. */
interface SVGTextElement extends SVGTextPositioningElement {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -13878,6 +14210,7 @@
new(): SVGTextElement;
};
+/** The SVGTextPathElement interface corresponds to the <textPath> element. */
interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference {
readonly method: SVGAnimatedEnumeration;
readonly spacing: SVGAnimatedEnumeration;
@@ -13905,6 +14238,7 @@
readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number;
};
+/** The SVGTextPositioningElement interface is implemented by elements that support attributes that position individual text glyphs. It is inherited by SVGTextElement, SVGTSpanElement, SVGTRefElement and SVGAltGlyphElement. */
interface SVGTextPositioningElement extends SVGTextContentElement {
readonly dx: SVGAnimatedLengthList;
readonly dy: SVGAnimatedLengthList;
@@ -13922,6 +14256,7 @@
new(): SVGTextPositioningElement;
};
+/** The SVGTitleElement interface corresponds to the <title> element. */
interface SVGTitleElement extends SVGElement {
addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -13934,6 +14269,7 @@
new(): SVGTitleElement;
};
+/** SVGTransform is the interface for one of the component transformations within an SVGTransformList; thus, an SVGTransform object corresponds to a single component (e.g., scale(…) or matrix(…)) within a transform attribute. */
interface SVGTransform {
readonly angle: number;
readonly matrix: SVGMatrix;
@@ -13965,6 +14301,7 @@
readonly SVG_TRANSFORM_UNKNOWN: number;
};
+/** The SVGTransformList defines a list of SVGTransform objects. */
interface SVGTransformList {
readonly numberOfItems: number;
appendItem(newItem: SVGTransform): SVGTransform;
@@ -13987,6 +14324,7 @@
readonly href: SVGAnimatedString;
}
+/** The SVGUnitTypes interface defines a commonly used set of constants used for reflecting gradientUnits, patternContentUnits and other similar attributes. */
interface SVGUnitTypes {
readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number;
readonly SVG_UNIT_TYPE_UNKNOWN: number;
@@ -14001,6 +14339,7 @@
readonly SVG_UNIT_TYPE_USERSPACEONUSE: number;
};
+/** The SVGUseElement interface corresponds to the <use> element. */
interface SVGUseElement extends SVGGraphicsElement, SVGURIReference {
readonly animatedInstanceRoot: SVGElementInstance | null;
readonly height: SVGAnimatedLength;
@@ -14019,6 +14358,7 @@
new(): SVGUseElement;
};
+/** The SVGViewElement interface provides access to the properties of <view> elements, as well as methods to manipulate them. */
interface SVGViewElement extends SVGElement, SVGFitToViewBox, SVGZoomAndPan {
/** @deprecated */
readonly viewTarget: SVGStringList;
@@ -14036,6 +14376,7 @@
readonly SVG_ZOOMANDPAN_UNKNOWN: number;
};
+/** The SVGZoomAndPan interface is used to reflect the zoomAndPan attribute, and is mixed in to other interfaces for elements that support this attribute. */
interface SVGZoomAndPan {
readonly zoomAndPan: number;
}
@@ -14079,6 +14420,7 @@
new(): ScopedCredentialInfo;
};
+/** The Screen interface represents a screen, usually the one on which the current window is being rendered, and is obtained using window.screen. */
interface Screen {
readonly availHeight: number;
readonly availWidth: number;
@@ -14119,6 +14461,7 @@
"audioprocess": AudioProcessingEvent;
}
+/** The ScriptProcessorNode interface allows the generation, processing, or analyzing of audio using JavaScript. */
interface ScriptProcessorNode extends AudioNode {
/** @deprecated */
readonly bufferSize: number;
@@ -14135,6 +14478,7 @@
new(): ScriptProcessorNode;
};
+/** The SecurityPolicyViolationEvent interface inherits from Event, and represents the event object of an event sent on a document or worker when its content security policy is violated. */
interface SecurityPolicyViolationEvent extends Event {
readonly blockedURI: string;
readonly columnNumber: number;
@@ -14153,33 +14497,29 @@
new(type: string, eventInitDict?: SecurityPolicyViolationEventInit): SecurityPolicyViolationEvent;
};
+/** A Selection object represents the range of text selected by the user or the current position of the caret. To obtain a Selection object for examination or modification, call Window.getSelection(). */
interface Selection {
- readonly anchorNode: Node;
+ readonly anchorNode: Node | null;
readonly anchorOffset: number;
- readonly baseNode: Node;
- readonly baseOffset: number;
- readonly extentNode: Node;
- readonly extentOffset: number;
- readonly focusNode: Node;
+ readonly focusNode: Node | null;
readonly focusOffset: number;
readonly isCollapsed: boolean;
readonly rangeCount: number;
readonly type: string;
addRange(range: Range): void;
- collapse(parentNode: Node, offset: number): void;
+ collapse(node: Node | null, offset?: number): void;
collapseToEnd(): void;
collapseToStart(): void;
- containsNode(node: Node, partlyContained: boolean): boolean;
+ containsNode(node: Node, allowPartialContainment?: boolean): boolean;
deleteFromDocument(): void;
empty(): void;
- extend(newNode: Node, offset: number): void;
+ extend(node: Node, offset?: number): void;
getRangeAt(index: number): Range;
removeAllRanges(): void;
removeRange(range: Range): void;
- selectAllChildren(parentNode: Node): void;
- setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void;
- setPosition(parentNode: Node, offset: number): void;
- toString(): string;
+ selectAllChildren(node: Node): void;
+ setBaseAndExtent(anchorNode: Node, anchorOffset: number, focusNode: Node, focusOffset: number): void;
+ setPosition(node: Node | null, offset?: number): void;
}
declare var Selection: {
@@ -14197,6 +14537,7 @@
"statechange": Event;
}
+/** The ServiceWorker interface of the ServiceWorker API provides a reference to a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same service worker, each through a unique ServiceWorker object. */
interface ServiceWorker extends EventTarget, AbstractWorker {
onstatechange: ((this: ServiceWorker, ev: Event) => any) | null;
readonly scriptURL: string;
@@ -14219,6 +14560,7 @@
"messageerror": MessageEvent;
}
+/** The ServiceWorkerContainer interface of the ServiceWorker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations. */
interface ServiceWorkerContainer extends EventTarget {
readonly controller: ServiceWorker | null;
oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null;
@@ -14240,6 +14582,7 @@
new(): ServiceWorkerContainer;
};
+/** The ServiceWorkerMessageEvent interface of the ServiceWorker API contains information about an event sent to a ServiceWorkerContainer target. This extends the default message event to allow setting a ServiceWorker object as the source of a message. The event object is accessed via the handler function of a message event, when fired by a message received from a service worker. */
interface ServiceWorkerMessageEvent extends Event {
readonly data: any;
readonly lastEventId: string;
@@ -14257,6 +14600,7 @@
"updatefound": Event;
}
+/** The ServiceWorkerRegistration interface of the ServiceWorker API represents the service worker registration. You register a service worker to control one or more pages that share the same origin. */
interface ServiceWorkerRegistration extends EventTarget {
readonly active: ServiceWorker | null;
readonly installing: ServiceWorker | null;
@@ -14282,35 +14626,52 @@
new(): ServiceWorkerRegistration;
};
-interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment, DocumentOrShadowRoot {
+interface ShadowRoot extends DocumentFragment, DocumentOrShadowRoot {
readonly host: Element;
innerHTML: string;
readonly mode: ShadowRootMode;
}
-interface ShadowRootInit {
- delegatesFocus?: boolean;
- mode: "open" | "closed";
-}
+declare var ShadowRoot: {
+ prototype: ShadowRoot;
+ new(): ShadowRoot;
+};
interface Slotable {
readonly assignedSlot: HTMLSlotElement | null;
}
+interface SourceBufferEventMap {
+ "abort": Event;
+ "error": Event;
+ "update": Event;
+ "updateend": Event;
+ "updatestart": Event;
+}
+
+/** The SourceBuffer interface represents a chunk of media to be passed into an HTMLMediaElement and played, via a MediaSource object. This can be made up of one or several media segments. */
interface SourceBuffer extends EventTarget {
appendWindowEnd: number;
appendWindowStart: number;
readonly audioTracks: AudioTrackList;
readonly buffered: TimeRanges;
mode: AppendMode;
+ onabort: ((this: SourceBuffer, ev: Event) => any) | null;
+ onerror: ((this: SourceBuffer, ev: Event) => any) | null;
+ onupdate: ((this: SourceBuffer, ev: Event) => any) | null;
+ onupdateend: ((this: SourceBuffer, ev: Event) => any) | null;
+ onupdatestart: ((this: SourceBuffer, ev: Event) => any) | null;
readonly textTracks: TextTrackList;
timestampOffset: number;
readonly updating: boolean;
readonly videoTracks: VideoTrackList;
abort(): void;
- appendBuffer(data: ArrayBuffer | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;
- appendStream(stream: MSStream, maxSize?: number): void;
+ appendBuffer(data: BufferSource): void;
remove(start: number, end: number): void;
+ addEventListener<K extends keyof SourceBufferEventMap>(type: K, listener: (this: SourceBuffer, ev: SourceBufferEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
+ removeEventListener<K extends keyof SourceBufferEventMap>(type: K, listener: (this: SourceBuffer, ev: SourceBufferEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}
declare var SourceBuffer: {
@@ -14318,9 +14679,20 @@
new(): SourceBuffer;
};
+interface SourceBufferListEventMap {
+ "addsourcebuffer": Event;
+ "removesourcebuffer": Event;
+}
+
+/** The SourceBufferList interface represents a simple container list for multiple SourceBuffer objects. */
interface SourceBufferList extends EventTarget {
readonly length: number;
- item(index: number): SourceBuffer;
+ onaddsourcebuffer: ((this: SourceBufferList, ev: Event) => any) | null;
+ onremovesourcebuffer: ((this: SourceBufferList, ev: Event) => any) | null;
+ addEventListener<K extends keyof SourceBufferListEventMap>(type: K, listener: (this: SourceBufferList, ev: SourceBufferListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
+ removeEventListener<K extends keyof SourceBufferListEventMap>(type: K, listener: (this: SourceBufferList, ev: SourceBufferListEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
[index: number]: SourceBuffer;
}
@@ -14457,6 +14829,7 @@
"voiceschanged": Event;
}
+/** The SpeechSynthesis interface of the Web Speech API is the controller interface for the speech service; this can be used to retrieve information about the synthesis voices available on the device, start and pause speech, and other commands besides. */
interface SpeechSynthesis extends EventTarget {
onvoiceschanged: ((this: SpeechSynthesis, ev: Event) => any) | null;
readonly paused: boolean;
@@ -14487,6 +14860,7 @@
new(): SpeechSynthesisErrorEvent;
};
+/** The SpeechSynthesisEvent interface of the Web Speech API contains information about the current state of SpeechSynthesisUtterance objects that have been processed in the speech service. */
interface SpeechSynthesisEvent extends Event {
readonly charIndex: number;
readonly elapsedTime: number;
@@ -14509,6 +14883,7 @@
"start": SpeechSynthesisEvent;
}
+/** The SpeechSynthesisUtterance interface of the Web Speech API represents a speech request. It contains the content the speech service should read and information about how to read it (e.g. language, pitch and volume.) */
interface SpeechSynthesisUtterance extends EventTarget {
lang: string;
onboundary: ((this: SpeechSynthesisUtterance, ev: SpeechSynthesisEvent) => any) | null;
@@ -14535,6 +14910,7 @@
new(text: string): SpeechSynthesisUtterance;
};
+/** The SpeechSynthesisVoice interface of the Web Speech API represents a voice that the system supports. Every SpeechSynthesisVoice has its own relative speech service including information about language, name and URI. */
interface SpeechSynthesisVoice {
readonly default: boolean;
readonly lang: string;
@@ -14556,6 +14932,7 @@
new(): StaticRange;
};
+/** The pan property takes a unitless value between -1 (full left pan) and 1 (full right pan). This interface was introduced as a much simpler way to apply a simple panning effect than having to use a full PannerNode. */
interface StereoPannerNode extends AudioNode {
readonly pan: AudioParam;
}
@@ -14565,6 +14942,7 @@
new(context: BaseAudioContext, options?: StereoPannerOptions): StereoPannerNode;
};
+/** The Storage interface of the Web Storage API provides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items. */
interface Storage {
/**
* Returns the number of key/value pairs currently present in the list associated with the
@@ -14600,6 +14978,7 @@
new(): Storage;
};
+/** A StorageEvent is sent to a window when a storage area it has access to is changed within the context of another document. */
interface StorageEvent extends Event {
/**
* Returns the key of the storage item being changed.
@@ -14649,6 +15028,7 @@
new(): StyleMedia;
};
+/** An object implementing the StyleSheet interface represents a single style sheet. CSS style sheets will further implement the more specialized CSSStyleSheet interface. */
interface StyleSheet {
disabled: boolean;
readonly href: string | null;
@@ -14664,6 +15044,7 @@
new(): StyleSheet;
};
+/** The StyleSheetList interface represents a list of StyleSheet. */
interface StyleSheetList {
readonly length: number;
item(index: number): StyleSheet | null;
@@ -14675,6 +15056,7 @@
new(): StyleSheetList;
};
+/** The SubtleCrypto interface represents a set of cryptographic primitives. It is available via the Crypto.subtle properties available in a window context (via Window.crypto). */
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<ArrayBuffer>;
deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike<ArrayBuffer>;
@@ -14701,6 +15083,7 @@
new(): SubtleCrypto;
};
+/** The SyncManager interface of the the ServiceWorker API provides an interface for registering and listing sync registrations. */
interface SyncManager {
getTags(): Promise<string[]>;
register(tag: string): Promise<void>;
@@ -14711,6 +15094,7 @@
new(): SyncManager;
};
+/** The Text interface represents the textual content of Element or Attr.  If an element has no markup within its content, it has a single child implementing Text that contains the element's text.  However, if the element contains markup, it is parsed into information items and Text nodes that form its children. */
interface Text extends CharacterData, Slotable {
readonly assignedSlot: HTMLSlotElement | null;
/**
@@ -14728,6 +15112,7 @@
new(data?: string): Text;
};
+/** The TextDecoder interface represents a decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, etc. A decoder takes a stream of bytes as input and emits a stream of code points. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. */
interface TextDecoder {
/**
* Returns encoding's name, lowercased.
@@ -14763,6 +15148,7 @@
new(label?: string, options?: TextDecoderOptions): TextDecoder;
};
+/** TextEncoder takes a stream of code points as input and emits a stream of bytes. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. */
interface TextEncoder {
/**
* Returns "utf-8".
@@ -14809,6 +15195,7 @@
readonly DOM_INPUT_METHOD_VOICE: number;
};
+/** The TextMetrics interface represents the dimension of a text in the canvas, as created by the CanvasRenderingContext2D.measureText() method. */
interface TextMetrics {
readonly actualBoundingBoxAscent: number;
readonly actualBoundingBoxDescent: number;
@@ -14838,6 +15225,7 @@
"load": Event;
}
+/** This interface also inherits properties from EventTarget. */
interface TextTrack extends EventTarget {
readonly activeCues: TextTrackCueList;
readonly cues: TextTrackCueList;
@@ -14850,6 +15238,7 @@
onerror: ((this: TextTrack, ev: Event) => any) | null;
onload: ((this: TextTrack, ev: Event) => any) | null;
readonly readyState: number;
+ readonly sourceBuffer: SourceBuffer | null;
addCue(cue: TextTrackCue): void;
removeCue(cue: TextTrackCue): void;
readonly DISABLED: number;
@@ -14882,6 +15271,7 @@
"exit": Event;
}
+/** TextTrackCues represent a string of text that will be displayed for some duration of time on a TextTrack. This includes the start and end times that the cue will be displayed. A TextTrackCue cannot be used directly, instead one of the derived types (e.g. VTTCue) must be used. */
interface TextTrackCue extends EventTarget {
endTime: number;
id: string;
@@ -14935,6 +15325,7 @@
new(): TextTrackList;
};
+/** The TimeRanges interface is used to represent a set of time ranges, primarily for the purpose of tracking which portions of media have been buffered when loading it for use by the <audio> and <video> elements. */
interface TimeRanges {
readonly length: number;
end(index: number): number;
@@ -14946,6 +15337,7 @@
new(): TimeRanges;
};
+/** The Touch interface represents a single contact point on a touch-sensitive device. The contact point is commonly a finger or stylus and the device may be a touchscreen or trackpad. */
interface Touch {
readonly altitudeAngle: number;
readonly azimuthAngle: number;
@@ -14969,6 +15361,7 @@
new(touchInitDict: TouchInit): Touch;
};
+/** The TouchEvent interface represents an event sent when the state of contacts with a touch-sensitive surface changes. This surface can be a touch screen or trackpad, for example. The event can describe one or more points of contact with the screen and includes support for detecting movement, addition and removal of contact points, and so forth. */
interface TouchEvent extends UIEvent {
readonly altKey: boolean;
readonly changedTouches: TouchList;
@@ -14984,6 +15377,7 @@
new(type: string, eventInitDict?: TouchEventInit): TouchEvent;
};
+/** The TouchList interface represents a list of contact points with a touch surface; for example, if the user has three fingers on the touch surface (such as a screen or trackpad), the corresponding TouchList object would have one Touch object for each finger, for a total of three entries. */
interface TouchList {
readonly length: number;
item(index: number): Touch | null;
@@ -14995,6 +15389,7 @@
new(): TouchList;
};
+/** The TrackEvent interface, part of the HTML DOM specification, is used for events which represent changes to the set of available tracks on an HTML media element; these events are addtrack and removetrack. */
interface TrackEvent extends Event {
readonly track: VideoTrack | AudioTrack | TextTrack | null;
}
@@ -15021,6 +15416,7 @@
terminate(): void;
}
+/** The TransitionEvent interface represents events providing information related to transitions. */
interface TransitionEvent extends Event {
readonly elapsedTime: number;
readonly propertyName: string;
@@ -15032,6 +15428,7 @@
new(type: string, transitionEventInitDict?: TransitionEventInit): TransitionEvent;
};
+/** The TreeWalker object represents the nodes of a document subtree and a position within them. */
interface TreeWalker {
currentNode: Node;
readonly filter: NodeFilter | null;
@@ -15051,6 +15448,7 @@
new(): TreeWalker;
};
+/** The UIEvent interface represents simple user interface events. */
interface UIEvent extends Event {
readonly detail: number;
readonly view: Window;
@@ -15062,6 +15460,7 @@
new(typeArg: string, eventInitDict?: UIEventInit): UIEvent;
};
+/** The URL interface represents an object providing static methods used for creating object URLs. */
interface URL {
hash: string;
host: string;
@@ -15122,6 +15521,7 @@
new(init?: string[][] | Record<string, string> | string | URLSearchParams): URLSearchParams;
};
+/** The VRDisplay interface of the WebVR API represents any VR device supported by this API. It includes generic information such as device IDs and descriptions, as well as methods for starting to present a VR scene, retrieving eye parameters and display capabilities, and other important functionality. */
interface VRDisplay extends EventTarget {
readonly capabilities: VRDisplayCapabilities;
depthFar: number;
@@ -15149,6 +15549,7 @@
new(): VRDisplay;
};
+/** The VRDisplayCapabilities interface of the WebVR API describes the capabilities of a VRDisplay — its features can be used to perform VR device capability tests, for example can it return position information. */
interface VRDisplayCapabilities {
readonly canPresent: boolean;
readonly hasExternalDisplay: boolean;
@@ -15162,6 +15563,7 @@
new(): VRDisplayCapabilities;
};
+/** The VRDisplayEvent interface of the WebVR API represents represents the event object of WebVR-related events (see the list of WebVR window extensions). */
interface VRDisplayEvent extends Event {
readonly display: VRDisplay;
readonly reason: VRDisplayEventReason | null;
@@ -15172,6 +15574,7 @@
new(type: string, eventInitDict: VRDisplayEventInit): VRDisplayEvent;
};
+/** The VREyeParameters interface of the WebVR API represents all the information required to correctly render a scene for a given eye, including field of view information. */
interface VREyeParameters {
/** @deprecated */
readonly fieldOfView: VRFieldOfView;
@@ -15185,6 +15588,7 @@
new(): VREyeParameters;
};
+/** The VRFieldOfView interface of the WebVR API represents a field of view defined by 4 different degree values describing the view from a center point. */
interface VRFieldOfView {
readonly downDegrees: number;
readonly leftDegrees: number;
@@ -15197,6 +15601,7 @@
new(): VRFieldOfView;
};
+/** The VRFrameData interface of the WebVR API represents all the information needed to render a single frame of a VR scene; constructed by VRDisplay.getFrameData(). */
interface VRFrameData {
readonly leftProjectionMatrix: Float32Array;
readonly leftViewMatrix: Float32Array;
@@ -15211,6 +15616,7 @@
new(): VRFrameData;
};
+/** The VRPose interface of the WebVR API represents the state of a VR sensor at a given timestamp (which includes orientation, position, velocity, and acceleration information.) */
interface VRPose {
readonly angularAcceleration: Float32Array | null;
readonly angularVelocity: Float32Array | null;
@@ -15265,6 +15671,7 @@
new(): VTTRegion;
};
+/** The ValidityState interface represents the validity states that an element can be in, with respect to constraint validation. Together, they help explain why an element's value fails to validate, if it's not valid. */
interface ValidityState {
readonly badInput: boolean;
readonly customError: boolean;
@@ -15284,6 +15691,7 @@
new(): ValidityState;
};
+/** A VideoPlaybackQuality object is returned by the HTMLVideoElement.getVideoPlaybackQuality() method and contains metrics that can be used to determine the playback quality of a video. */
interface VideoPlaybackQuality {
readonly corruptedVideoFrames: number;
readonly creationTime: number;
@@ -15297,13 +15705,14 @@
new(): VideoPlaybackQuality;
};
+/** The VideoTrack interface represents a single video track from a <video> element. */
interface VideoTrack {
readonly id: string;
kind: string;
readonly label: string;
language: string;
selected: boolean;
- readonly sourceBuffer: SourceBuffer;
+ readonly sourceBuffer: SourceBuffer | null;
}
declare var VideoTrack: {
@@ -15317,6 +15726,7 @@
"removetrack": TrackEvent;
}
+/** The VideoTrackList interface is used to represent a list of the video tracks contained within a <video> element, with each track represented by a separate VideoTrack object in the list. */
interface VideoTrackList extends EventTarget {
readonly length: number;
onaddtrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null;
@@ -15375,6 +15785,7 @@
readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: GLenum;
}
+/** The WEBGL_compressed_texture_s3tc extension is part of the WebGL API and exposes four S3TC compressed texture formats. */
interface WEBGL_compressed_texture_s3tc {
readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: GLenum;
readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: GLenum;
@@ -15389,6 +15800,7 @@
readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: GLenum;
}
+/** The WEBGL_debug_renderer_info extension is part of the WebGL API and exposes two constants with information about the graphics driver for debugging purposes. */
interface WEBGL_debug_renderer_info {
readonly UNMASKED_RENDERER_WEBGL: GLenum;
readonly UNMASKED_VENDOR_WEBGL: GLenum;
@@ -15398,6 +15810,7 @@
getTranslatedShaderSource(shader: WebGLShader): string;
}
+/** The WEBGL_depth_texture extension is part of the WebGL API and defines 2D depth and depth-stencil textures. */
interface WEBGL_depth_texture {
readonly UNSIGNED_INT_24_8_WEBGL: GLenum;
}
@@ -15445,6 +15858,7 @@
restoreContext(): void;
}
+/** A WaveShaperNode always has exactly one input and one output. */
interface WaveShaperNode extends AudioNode {
curve: Float32Array | null;
oversample: OverSampleType;
@@ -15477,6 +15891,7 @@
new(): WebAuthnAssertion;
};
+/** The WebGLActiveInfo interface is part of the WebGL API and represents the information returned by calling the WebGLRenderingContext.getActiveAttrib() and WebGLRenderingContext.getActiveUniform() methods. */
interface WebGLActiveInfo {
readonly name: string;
readonly size: GLint;
@@ -15488,6 +15903,7 @@
new(): WebGLActiveInfo;
};
+/** The WebGLBuffer interface is part of the WebGL API and represents an opaque buffer object storing data such as vertices or colors. */
interface WebGLBuffer extends WebGLObject {
}
@@ -15496,6 +15912,7 @@
new(): WebGLBuffer;
};
+/** The WebContextEvent interface is part of the WebGL API and is an interface for an event that is generated in response to a status change to the WebGL rendering context. */
interface WebGLContextEvent extends Event {
readonly statusMessage: string;
}
@@ -15505,6 +15922,7 @@
new(type: string, eventInit?: WebGLContextEventInit): WebGLContextEvent;
};
+/** The WebGLFramebuffer interface is part of the WebGL API and represents a collection of buffers that serve as a rendering destination. */
interface WebGLFramebuffer extends WebGLObject {
}
@@ -15521,6 +15939,7 @@
new(): WebGLObject;
};
+/** The WebGLProgram is part of the WebGL API and is a combination of two compiled WebGLShaders consisting of a vertex shader and a fragment shader (both written in GLSL). */
interface WebGLProgram extends WebGLObject {
}
@@ -15529,6 +15948,7 @@
new(): WebGLProgram;
};
+/** The WebGLRenderbuffer interface is part of the WebGL API and represents a buffer that can contain an image, or can be source or target of an rendering operation. */
interface WebGLRenderbuffer extends WebGLObject {
}
@@ -15537,6 +15957,7 @@
new(): WebGLRenderbuffer;
};
+/** The WebGLRenderingContext interface provides an interface to the OpenGL ES 2.0 graphics rendering context for the drawing surface of an HTML <canvas> element. */
interface WebGLRenderingContext extends WebGLRenderingContextBase {
}
@@ -15956,7 +16377,7 @@
isTexture(texture: WebGLTexture | null): GLboolean;
lineWidth(width: GLfloat): void;
linkProgram(program: WebGLProgram): void;
- pixelStorei(pname: GLenum, param: GLint): void;
+ pixelStorei(pname: GLenum, param: GLint | GLboolean): 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;
@@ -16304,6 +16725,7 @@
readonly ZERO: GLenum;
}
+/** The WebGLShader is part of the WebGL API and can either be a vertex or a fragment shader. A WebGLProgram requires both types of shaders. */
interface WebGLShader extends WebGLObject {
}
@@ -16312,6 +16734,7 @@
new(): WebGLShader;
};
+/** The WebGLShaderPrecisionFormat interface is part of the WebGL API and represents the information returned by calling the WebGLRenderingContext.getShaderPrecisionFormat() method. */
interface WebGLShaderPrecisionFormat {
readonly precision: GLint;
readonly rangeMax: GLint;
@@ -16323,6 +16746,7 @@
new(): WebGLShaderPrecisionFormat;
};
+/** The WebGLTexture interface is part of the WebGL API and represents an opaque texture object providing storage and state for texturing operations. */
interface WebGLTexture extends WebGLObject {
}
@@ -16331,6 +16755,7 @@
new(): WebGLTexture;
};
+/** The WebGLUniformLocation interface is part of the WebGL API and represents the location of a uniform variable in a shader program. */
interface WebGLUniformLocation {
}
@@ -16359,6 +16784,7 @@
"open": Event;
}
+/** The WebSocket object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. */
interface WebSocket extends EventTarget {
binaryType: BinaryType;
readonly bufferedAmount: number;
@@ -16391,6 +16817,7 @@
readonly OPEN: number;
};
+/** The WheelEvent interface represents events that occur due to the user moving a mouse wheel or similar input device. */
interface WheelEvent extends MouseEvent {
readonly deltaMode: number;
readonly deltaX: number;
@@ -16487,10 +16914,10 @@
"readystatechange": ProgressEvent;
"reset": Event;
"resize": UIEvent;
- "scroll": UIEvent;
+ "scroll": Event;
"seeked": Event;
"seeking": Event;
- "select": UIEvent;
+ "select": Event;
"stalled": Event;
"storage": StorageEvent;
"submit": Event;
@@ -16510,6 +16937,7 @@
"waiting": Event;
}
+/** The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window. */
interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch, WindowOrWorkerGlobalScope, WindowEventHandlers {
Blob: typeof Blob;
URL: typeof URL;
@@ -16524,6 +16952,7 @@
readonly devicePixelRatio: number;
readonly doNotTrack: string;
readonly document: Document;
+ /** @deprecated */
readonly event: Event | undefined;
/** @deprecated */
readonly external: External;
@@ -16610,7 +17039,7 @@
focus(): void;
getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration;
getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList;
- getSelection(): Selection;
+ getSelection(): Selection | null;
matchMedia(query: string): MediaQueryList;
moveBy(x: number, y: number): void;
moveTo(x: number, y: number): void;
@@ -16730,6 +17159,7 @@
"message": MessageEvent;
}
+/** The Worker interface of the Web Workers API represents a background task that can be easily created and can send messages back to its creator. Creating a worker is as simple as calling the Worker() constructor and specifying a script to be run in the worker thread. */
interface Worker extends EventTarget, AbstractWorker {
onmessage: ((this: Worker, ev: MessageEvent) => any) | null;
postMessage(message: any, transfer?: Transferable[]): void;
@@ -16742,7 +17172,7 @@
declare var Worker: {
prototype: Worker;
- new(stringUrl: string, options?: WorkerOptions): Worker;
+ new(stringUrl: string | URL, options?: WorkerOptions): Worker;
};
interface Worklet {
@@ -16754,6 +17184,7 @@
new(): Worklet;
};
+/** The WritableStream interface of the the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing. */
interface WritableStream<W = any> {
readonly locked: boolean;
abort(reason?: any): Promise<void>;
@@ -16765,10 +17196,12 @@
new<W = any>(underlyingSink?: UnderlyingSink<W>, strategy?: QueuingStrategy<W>): WritableStream<W>;
};
+/** The WritableStreamDefaultController interface of the the Streams API represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate. */
interface WritableStreamDefaultController {
error(error?: any): void;
}
+/** The WritableStreamDefaultWriter interface of the the Streams API is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink. */
interface WritableStreamDefaultWriter<W = any> {
readonly closed: Promise<void>;
readonly desiredSize: number | null;
@@ -16779,6 +17212,7 @@
write(chunk: W): Promise<void>;
}
+/** The XMLDocument interface represent an XML document. It inherits from the generic Document and does not add any specific methods or properties to it: nevertheless, several algorithms behave differently with the two types of documents. */
interface XMLDocument extends Document {
addEventListener<K extends keyof DocumentEventMap>(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -16795,6 +17229,7 @@
"readystatechange": Event;
}
+/** Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. */
interface XMLHttpRequest extends XMLHttpRequestEventTarget {
onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null;
/**
@@ -16874,7 +17309,8 @@
*/
overrideMimeType(mime: string): void;
/**
- * Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD.
+ * Initiates the request. The body argument provides the request body, if any,
+ * and is ignored if the 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 | null): void;
@@ -16947,6 +17383,7 @@
new(): XMLHttpRequestUpload;
};
+/** The XMLSerializer interface provides the serializeToString() method to construct an XML string representing a DOM tree. */
interface XMLSerializer {
serializeToString(root: Node): string;
}
@@ -16967,6 +17404,7 @@
new(): XPathEvaluator;
};
+/** An XPathExpression is a compiled XPath query returned from document.createExpression(). It has a method evaluate() which can be used to execute the compiled XPath. */
interface XPathExpression {
evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult;
}
@@ -16985,6 +17423,7 @@
new(): XPathNSResolver;
};
+/** The XPathResult interface represents the results generated by evaluating an XPath 1.0 expression within the context of a given node. */
interface XPathResult {
readonly booleanValue: boolean;
readonly invalidIteratorState: boolean;
@@ -17022,6 +17461,7 @@
readonly UNORDERED_NODE_SNAPSHOT_TYPE: number;
};
+/** An XSLTProcessor applies an XSLT stylesheet transformation to an XML document to produce a new XML document as output. It has methods to load the XSLT stylesheet, to manipulate <xsl:param> parameter values, and to apply the transformation to documents. */
interface XSLTProcessor {
clearParameters(): void;
getParameter(namespaceURI: string, localName: string): any;
@@ -17064,10 +17504,6 @@
(decodedData: AudioBuffer): void;
}
-interface ErrorEventHandler {
- (event: Event | string, source?: string, fileno?: number, columnNumber?: number, error?: Error): void;
-}
-
interface EventHandlerNonNull {
(event: Event): any;
}
@@ -17113,7 +17549,7 @@
}
interface OnErrorEventHandlerNonNull {
- (event: Event | string, source?: string, lineno?: number, colno?: number, error?: any): any;
+ (event: Event | string, source?: string, lineno?: number, colno?: number, error?: Error): any;
}
interface PerformanceObserverCallback {
@@ -17196,6 +17632,7 @@
"b": HTMLElement;
"base": HTMLBaseElement;
"basefont": HTMLBaseFontElement;
+ "bdi": HTMLElement;
"bdo": HTMLElement;
"blockquote": HTMLQuoteElement;
"body": HTMLBodyElement;
@@ -17249,6 +17686,7 @@
"legend": HTMLLegendElement;
"li": HTMLLIElement;
"link": HTMLLinkElement;
+ "main": HTMLElement;
"map": HTMLMapElement;
"mark": HTMLElement;
"marquee": HTMLMarqueeElement;
@@ -17268,6 +17706,7 @@
"pre": HTMLPreElement;
"progress": HTMLProgressElement;
"q": HTMLQuoteElement;
+ "rp": HTMLElement;
"rt": HTMLElement;
"ruby": HTMLElement;
"s": HTMLElement;
@@ -17282,6 +17721,7 @@
"strong": HTMLElement;
"style": HTMLStyleElement;
"sub": HTMLElement;
+ "summary": HTMLElement;
"sup": HTMLElement;
"table": HTMLTableElement;
"tbody": HTMLTableSectionElement;
@@ -17388,6 +17828,7 @@
declare var devicePixelRatio: number;
declare var doNotTrack: string;
declare var document: Document;
+/** @deprecated */
declare var event: Event | undefined;
/** @deprecated */
declare var external: External;
@@ -17474,7 +17915,7 @@
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 getSelection(): Selection | null;
declare function matchMedia(query: string): MediaQueryList;
declare function moveBy(x: number, y: number): void;
declare function moveTo(x: number, y: number): void;
@@ -17603,7 +18044,7 @@
* Fires when an error occurs during object loading.
* @param ev The event.
*/
-declare var onerror: ErrorEventHandler;
+declare var onerror: OnErrorEventHandler;
/**
* Fires when the object receives focus.
* @param ev The event.
@@ -17719,7 +18160,7 @@
* 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 onscroll: ((this: Window, ev: Event) => any) | null;
declare var onsecuritypolicyviolation: ((this: Window, ev: SecurityPolicyViolationEvent) => any) | null;
/**
* Occurs when the seek operation ends.
@@ -17735,7 +18176,9 @@
* Fires when the current selection changes.
* @param ev The event.
*/
-declare var onselect: ((this: Window, ev: UIEvent) => any) | null;
+declare var onselect: ((this: Window, ev: Event) => any) | null;
+declare var onselectionchange: ((this: Window, ev: Event) => any) | null;
+declare var onselectstart: ((this: Window, ev: Event) => any) | null;
/**
* Occurs when the download has stopped.
* @param ev The event.
@@ -17892,6 +18335,7 @@
type EndOfStreamError = "network" | "decode";
type EndingType = "transparent" | "native";
type FillMode = "none" | "forwards" | "backwards" | "both" | "auto";
+type FullscreenNavigationUI = "auto" | "show" | "hide";
type GamepadHand = "" | "left" | "right";
type GamepadHapticActuatorType = "vibration";
type GamepadInputEmulationType = "mouse" | "keyboard" | "gamepad";
@@ -17912,8 +18356,8 @@
type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications";
type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput";
type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request";
-type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message";
-type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error";
+type MediaKeySessionType = "temporary" | "persistent-license";
+type MediaKeyStatus = "usable" | "expired" | "released" | "output-restricted" | "output-downscaled" | "status-pending" | "internal-error";
type MediaKeysRequirement = "required" | "optional" | "not-allowed";
type MediaStreamTrackState = "live" | "ended";
type NavigationReason = "up" | "down" | "left" | "right";
@@ -17961,7 +18405,7 @@
type RTCStatsIceCandidateType = "host" | "serverreflexive" | "peerreflexive" | "relayed";
type RTCStatsType = "inboundrtp" | "outboundrtp" | "session" | "datachannel" | "track" | "transport" | "candidatepair" | "localcandidate" | "remotecandidate";
type ReadyState = "closed" | "open" | "ended";
-type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url";
+type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached";
type RequestCredentials = "omit" | "same-origin" | "include";
type RequestDestination = "" | "audio" | "audioworklet" | "document" | "embed" | "font" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt";

lib/lib.dom.iterable.d.ts

@@ -116,6 +116,13 @@
values(): IterableIterator<string>;
}
+interface MediaKeyStatusMap {
+ [Symbol.iterator](): IterableIterator<[BufferSource, MediaKeyStatus]>;
+ entries(): IterableIterator<[BufferSource, MediaKeyStatus]>;
+ keys(): IterableIterator<BufferSource>;
+ values(): IterableIterator<MediaKeyStatus>;
+}
+
interface MediaList {
[Symbol.iterator](): IterableIterator<string>;
}

lib/lib.es2015.collection.d.ts

@@ -30,7 +30,7 @@
interface MapConstructor {
new(): Map<any, any>;
- new<K, V>(entries?: ReadonlyArray<[K, V]> | null): Map<K, V>;
+ new<K, V>(entries?: ReadonlyArray<readonly [K, V]> | null): Map<K, V>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;

lib/lib.es2015.iterable.d.ts

@@ -149,7 +149,7 @@
}
interface MapConstructor {
- new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>;
+ new <K, V>(iterable: Iterable<readonly [K, V]>): Map<K, V>;
}
interface WeakMap<K extends object, V> { }

lib/lib.es2017.sharedmemory.d.ts

@@ -123,7 +123,7 @@
* Wakes up sleeping agents that are waiting on the given index of the array, returning the
* number of agents that were awoken.
*/
- wake(typedArray: Int32Array, index: number, count: number): number;
+ notify(typedArray: Int32Array, index: number, count: number): number;
/**
* Stores the bitwise XOR of a value with the value at the given position in the array,

lib/lib.es2018.asynciterable.d.ts

@@ -0,0 +1,44 @@
+/*! *****************************************************************************
+Copyright (c) Microsoft Corporation. All rights reserved.
+Licensed under the Apache License, Version 2.0 (the "License"); you may not use
+this file except in compliance with the License. You may obtain a copy of the
+License at http://www.apache.org/licenses/LICENSE-2.0
+
+THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+MERCHANTABLITY OR NON-INFRINGEMENT.
+
+See the Apache Version 2.0 License for specific language governing permissions
+and limitations under the License.
+***************************************************************************** */
+
+
+
+/// <reference no-default-lib="true"/>
+
+
+/// <reference lib="es2015.symbol" />
+/// <reference lib="es2015.iterable" />
+
+interface SymbolConstructor {
+ /**
+ * A method that returns the default async iterator for an object. Called by the semantics of
+ * the for-await-of statement.
+ */
+ readonly asyncIterator: symbol;
+}
+
+interface AsyncIterator<T> {
+ next(value?: any): Promise<IteratorResult<T>>;
+ return?(value?: any): Promise<IteratorResult<T>>;
+ throw?(e?: any): Promise<IteratorResult<T>>;
+}
+
+interface AsyncIterable<T> {
+ [Symbol.asyncIterator](): AsyncIterator<T>;
+}
+
+interface AsyncIterableIterator<T> extends AsyncIterator<T> {
+ [Symbol.asyncIterator](): AsyncIterableIterator<T>;
+}
\ No newline at end of file

lib/lib.es2018.d.ts

@@ -19,6 +19,7 @@
/// <reference lib="es2017" />
+/// <reference lib="es2018.asynciterable" />
/// <reference lib="es2018.promise" />
/// <reference lib="es2018.regexp" />
/// <reference lib="es2018.intl" />

lib/lib.es2019.array.d.ts

@@ -0,0 +1,223 @@
+/*! *****************************************************************************
+Copyright (c) Microsoft Corporation. All rights reserved.
+Licensed under the Apache License, Version 2.0 (the "License"); you may not use
+this file except in compliance with the License. You may obtain a copy of the
+License at http://www.apache.org/licenses/LICENSE-2.0
+
+THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+MERCHANTABLITY OR NON-INFRINGEMENT.
+
+See the Apache Version 2.0 License for specific language governing permissions
+and limitations under the License.
+***************************************************************************** */
+
+
+
+/// <reference no-default-lib="true"/>
+
+
+interface ReadonlyArray<T> {
+
+ /**
+ * Calls a defined callback function on each element of an array. Then, flattens the result into
+ * a new array.
+ * This is identical to a map followed by flat with depth 1.
+ *
+ * @param callback A function that accepts up to three arguments. The flatMap method calls the
+ * callback function one time for each element in the array.
+ * @param thisArg An object to which the this keyword can refer in the callback function. If
+ * thisArg is omitted, undefined is used as the this value.
+ */
+ flatMap<U, This = undefined> (
+ callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray<U>,
+ thisArg?: This
+ ): U[]
+
+
+ /**
+ * Returns a new array with all sub-array elements concatenated into it recursively up to the
+ * specified depth.
+ *
+ * @param depth The maximum recursion depth
+ */
+ flat<U>(this:
+ ReadonlyArray<U[][][][]> |
+
+ ReadonlyArray<ReadonlyArray<U[][][]>> |
+ ReadonlyArray<ReadonlyArray<U[][]>[]> |
+ ReadonlyArray<ReadonlyArray<U[]>[][]> |
+ ReadonlyArray<ReadonlyArray<U>[][][]> |
+
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<U[][]>>> |
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<U>[][]>> |
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<U>>[][]> |
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<U>[]>[]> |
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<U[]>>[]> |
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<U[]>[]>> |
+
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<ReadonlyArray<U[]>>>> |
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<ReadonlyArray<U>[]>>> |
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<ReadonlyArray<U>>[]>> |
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<ReadonlyArray<U>>>[]> |
+
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<ReadonlyArray<ReadonlyArray<U>>>>>,
+ depth: 4): U[];
+
+ /**
+ * Returns a new array with all sub-array elements concatenated into it recursively up to the
+ * specified depth.
+ *
+ * @param depth The maximum recursion depth
+ */
+ flat<U>(this:
+ ReadonlyArray<U[][][]> |
+
+ ReadonlyArray<ReadonlyArray<U>[][]> |
+ ReadonlyArray<ReadonlyArray<U[]>[]> |
+ ReadonlyArray<ReadonlyArray<U[][]>> |
+
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<U[]>>> |
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<U>[]>> |
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<U>>[]> |
+
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<ReadonlyArray<U>>>>,
+ depth: 3): U[];
+
+ /**
+ * Returns a new array with all sub-array elements concatenated into it recursively up to the
+ * specified depth.
+ *
+ * @param depth The maximum recursion depth
+ */
+ flat<U>(this:
+ ReadonlyArray<U[][]> |
+
+ ReadonlyArray<ReadonlyArray<U[]>> |
+ ReadonlyArray<ReadonlyArray<U>[]> |
+
+ ReadonlyArray<ReadonlyArray<ReadonlyArray<U>>>,
+ depth: 2): U[];
+
+ /**
+ * Returns a new array with all sub-array elements concatenated into it recursively up to the
+ * specified depth.
+ *
+ * @param depth The maximum recursion depth
+ */
+ flat<U>(this:
+ ReadonlyArray<U[]> |
+ ReadonlyArray<ReadonlyArray<U>>,
+ depth?: 1
+ ): U[];
+
+ /**
+ * Returns a new array with all sub-array elements concatenated into it recursively up to the
+ * specified depth.
+ *
+ * @param depth The maximum recursion depth
+ */
+ flat<U>(this:
+ ReadonlyArray<U>,
+ depth: 0
+ ): U[];
+
+ /**
+ * Returns a new array with all sub-array elements concatenated into it recursively up to the
+ * specified depth. If no depth is provided, flat method defaults to the depth of 1.
+ *
+ * @param depth The maximum recursion depth
+ */
+ flat<U>(depth?: number): any[];
+ }
+
+interface Array<T> {
+
+ /**
+ * Calls a defined callback function on each element of an array. Then, flattens the result into
+ * a new array.
+ * This is identical to a map followed by flat with depth 1.
+ *
+ * @param callback A function that accepts up to three arguments. The flatMap method calls the
+ * callback function one time for each element in the array.
+ * @param thisArg An object to which the this keyword can refer in the callback function. If
+ * thisArg is omitted, undefined is used as the this value.
+ */
+ flatMap<U, This = undefined> (
+ callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray<U>,
+ thisArg?: This
+ ): U[]
+
+ /**
+ * Returns a new array with all sub-array elements concatenated into it recursively up to the
+ * specified depth.
+ *
+ * @param depth The maximum recursion depth
+ */
+ flat<U>(this: U[][][][][][][][], depth: 7): U[];
+
+ /**
+ * Returns a new array with all sub-array elements concatenated into it recursively up to the
+ * specified depth.
+ *
+ * @param depth The maximum recursion depth
+ */
+ flat<U>(this: U[][][][][][][], depth: 6): U[];
+
+ /**
+ * Returns a new array with all sub-array elements concatenated into it recursively up to the
+ * specified depth.
+ *
+ * @param depth The maximum recursion depth
+ */
+ flat<U>(this: U[][][][][][], depth: 5): U[];
+
+ /**
+ * Returns a new array with all sub-array elements concatenated into it recursively up to the
+ * specified depth.
+ *
+ * @param depth The maximum recursion depth
+ */
+ flat<U>(this: U[][][][][], depth: 4): U[];
+
+ /**
+ * Returns a new array with all sub-array elements concatenated into it recursively up to the
+ * specified depth.
+ *
+ * @param depth The maximum recursion depth
+ */
+ flat<U>(this: U[][][][], depth: 3): U[];
+
+ /**
+ * Returns a new array with all sub-array elements concatenated into it recursively up to the
+ * specified depth.
+ *
+ * @param depth The maximum recursion depth
+ */
+ flat<U>(this: U[][][], depth: 2): U[];
+
+ /**
+ * Returns a new array with all sub-array elements concatenated into it recursively up to the
+ * specified depth.
+ *
+ * @param depth The maximum recursion depth
+ */
+ flat<U>(this: U[][], depth?: 1): U[];
+
+ /**
+ * Returns a new array with all sub-array elements concatenated into it recursively up to the
+ * specified depth.
+ *
+ * @param depth The maximum recursion depth
+ */
+ flat<U>(this: U[], depth: 0): U[];
+
+ /**
+ * Returns a new array with all sub-array elements concatenated into it recursively up to the
+ * specified depth. If no depth is provided, flat method defaults to the depth of 1.
+ *
+ * @param depth The maximum recursion depth
+ */
+ flat<U>(depth?: number): any[];
+}

lib/lib.es2019.d.ts

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

lib/lib.es2019.full.d.ts

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

lib/lib.es2019.string.d.ts

@@ -0,0 +1,33 @@
+/*! *****************************************************************************
+Copyright (c) Microsoft Corporation. All rights reserved.
+Licensed under the Apache License, Version 2.0 (the "License"); you may not use
+this file except in compliance with the License. You may obtain a copy of the
+License at http://www.apache.org/licenses/LICENSE-2.0
+
+THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+MERCHANTABLITY OR NON-INFRINGEMENT.
+
+See the Apache Version 2.0 License for specific language governing permissions
+and limitations under the License.
+***************************************************************************** */
+
+
+
+/// <reference no-default-lib="true"/>
+
+
+interface String {
+ /** Removes the trailing white space and line terminator characters from a string. */
+ trimEnd(): string;
+
+ /** Removes the leading white space and line terminator characters from a string. */
+ trimStart(): string;
+
+ /** Removes the trailing white space and line terminator characters from a string. */
+ trimLeft(): string;
+
+ /** Removes the leading white space and line terminator characters from a string. */
+ trimRight(): string;
+}

lib/lib.es2019.symbol.d.ts

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

lib/lib.es5.d.ts

@@ -22,8 +22,8 @@
/// ECMAScript APIs
/////////////////////////////
-declare const NaN: number;
-declare const Infinity: number;
+declare var NaN: number;
+declare var Infinity: number;
/**
* Evaluates JavaScript code and executes it.
@@ -264,7 +264,7 @@
/**
* Provides functionality common to all JavaScript objects.
*/
-declare const Object: ObjectConstructor;
+declare var Object: ObjectConstructor;
/**
* Creates a new function.
@@ -313,7 +313,7 @@
readonly prototype: Function;
}
-declare const Function: FunctionConstructor;
+declare var Function: FunctionConstructor;
/**
* Extracts the type of the 'this' parameter of a function type, or 'unknown' if the function type has no 'this' parameter.
@@ -524,7 +524,7 @@
/**
* Allows manipulation and formatting of text strings and determination and location of substrings within strings.
*/
-declare const String: StringConstructor;
+declare var String: StringConstructor;
interface Boolean {
/** Returns the primitive value of the specified object. */
@@ -537,7 +537,7 @@
readonly prototype: Boolean;
}
-declare const Boolean: BooleanConstructor;
+declare var Boolean: BooleanConstructor;
interface Number {
/**
@@ -599,7 +599,7 @@
}
/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */
-declare const Number: NumberConstructor;
+declare var Number: NumberConstructor;
interface TemplateStringsArray extends ReadonlyArray<string> {
readonly raw: ReadonlyArray<string>;
@@ -723,7 +723,7 @@
tan(x: number): number;
}
/** An intrinsic object that provides basic mathematics functionality and constants. */
-declare const Math: Math;
+declare var Math: Math;
/** Enables basic storage and retrieval of dates and times. */
interface Date {
@@ -904,7 +904,7 @@
now(): number;
}
-declare const Date: DateConstructor;
+declare var Date: DateConstructor;
interface RegExpMatchArray extends Array<string> {
index?: number;
@@ -967,7 +967,7 @@
lastMatch: string;
}
-declare const RegExp: RegExpConstructor;
+declare var RegExp: RegExpConstructor;
interface Error {
name: string;
@@ -981,7 +981,7 @@
readonly prototype: Error;
}
-declare const Error: ErrorConstructor;
+declare var Error: ErrorConstructor;
interface EvalError extends Error {
}
@@ -992,7 +992,7 @@
readonly prototype: EvalError;
}
-declare const EvalError: EvalErrorConstructor;
+declare var EvalError: EvalErrorConstructor;
interface RangeError extends Error {
}
@@ -1003,7 +1003,7 @@
readonly prototype: RangeError;
}
-declare const RangeError: RangeErrorConstructor;
+declare var RangeError: RangeErrorConstructor;
interface ReferenceError extends Error {
}
@@ -1014,7 +1014,7 @@
readonly prototype: ReferenceError;
}
-declare const ReferenceError: ReferenceErrorConstructor;
+declare var ReferenceError: ReferenceErrorConstructor;
interface SyntaxError extends Error {
}
@@ -1025,7 +1025,7 @@
readonly prototype: SyntaxError;
}
-declare const SyntaxError: SyntaxErrorConstructor;
+declare var SyntaxError: SyntaxErrorConstructor;
interface TypeError extends Error {
}
@@ -1036,7 +1036,7 @@
readonly prototype: TypeError;
}
-declare const TypeError: TypeErrorConstructor;
+declare var TypeError: TypeErrorConstructor;
interface URIError extends Error {
}
@@ -1047,7 +1047,7 @@
readonly prototype: URIError;
}
-declare const URIError: URIErrorConstructor;
+declare var URIError: URIErrorConstructor;
interface JSON {
/**
@@ -1056,14 +1056,14 @@
* @param reviver A function that transforms the results. This function is called for each member of the object.
* If a member contains nested objects, the nested objects are transformed before the parent object is.
*/
- parse(text: string, reviver?: (key: any, value: any) => any): any;
+ parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer A function that transforms the results.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
- stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string;
+ stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
@@ -1076,7 +1076,7 @@
/**
* An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
*/
-declare const JSON: JSON;
+declare var JSON: JSON;
/////////////////////////////
@@ -1134,13 +1134,13 @@
* @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
- every(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => boolean, thisArg?: any): boolean;
+ every(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => unknown, thisArg?: any): boolean;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
- some(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => boolean, thisArg?: any): boolean;
+ some(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => unknown, thisArg?: any): boolean;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
@@ -1164,7 +1164,7 @@
* @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
- filter(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => any, thisArg?: any): T[];
+ filter(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => unknown, thisArg?: any): T[];
/**
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
@@ -1365,7 +1365,7 @@
readonly prototype: Array<any>;
}
-declare const Array: ArrayConstructor;
+declare var Array: ArrayConstructor;
interface TypedPropertyDescriptor<T> {
enumerable?: boolean;
@@ -1471,22 +1471,22 @@
/**
* Obtain the parameters of a function type in a tuple
*/
-type Parameters<T extends (...args: any[]) => any> = T extends (...args: infer P) => any ? P : never;
+type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;
/**
* Obtain the parameters of a constructor function type in a tuple
*/
-type ConstructorParameters<T extends new (...args: any[]) => any> = T extends new (...args: infer P) => any ? P : never;
+type ConstructorParameters<T extends new (...args: any) => any> = T extends new (...args: infer P) => any ? P : never;
/**
* Obtain the return type of a function type
*/
-type ReturnType<T extends (...args: any[]) => any> = T extends (...args: any[]) => infer R ? R : any;
+type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
/**
* Obtain the return type of a constructor function type
*/
-type InstanceType<T extends new (...args: any[]) => any> = T extends new (...args: any[]) => infer R ? R : any;
+type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;
/**
* Marker for contextual 'this' type
@@ -1524,7 +1524,7 @@
new(byteLength: number): ArrayBuffer;
isView(arg: any): arg is ArrayBufferView;
}
-declare const ArrayBuffer: ArrayBufferConstructor;
+declare var ArrayBuffer: ArrayBufferConstructor;
interface ArrayBufferView {
/**
@@ -1674,7 +1674,7 @@
interface DataViewConstructor {
new(buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView;
}
-declare const DataView: DataViewConstructor;
+declare var DataView: DataViewConstructor;
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
@@ -1949,7 +1949,7 @@
}
-declare const Int8Array: Int8ArrayConstructor;
+declare var Int8Array: Int8ArrayConstructor;
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
@@ -2224,7 +2224,7 @@
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8Array;
}
-declare const Uint8Array: Uint8ArrayConstructor;
+declare var Uint8Array: Uint8ArrayConstructor;
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
@@ -2498,7 +2498,7 @@
*/
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8ClampedArray;
}
-declare const Uint8ClampedArray: Uint8ClampedArrayConstructor;
+declare var Uint8ClampedArray: Uint8ClampedArrayConstructor;
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
@@ -2773,7 +2773,7 @@
}
-declare const Int16Array: Int16ArrayConstructor;
+declare var Int16Array: Int16ArrayConstructor;
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
@@ -3049,7 +3049,7 @@
}
-declare const Uint16Array: Uint16ArrayConstructor;
+declare var Uint16Array: Uint16ArrayConstructor;
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
@@ -3323,7 +3323,7 @@
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Int32Array;
}
-declare const Int32Array: Int32ArrayConstructor;
+declare var Int32Array: Int32ArrayConstructor;
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
@@ -3597,7 +3597,7 @@
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Uint32Array;
}
-declare const Uint32Array: Uint32ArrayConstructor;
+declare var Uint32Array: Uint32ArrayConstructor;
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
@@ -3873,7 +3873,7 @@
}
-declare const Float32Array: Float32ArrayConstructor;
+declare var Float32Array: Float32ArrayConstructor;
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
@@ -4148,7 +4148,7 @@
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Float64Array;
}
-declare const Float64Array: Float64ArrayConstructor;
+declare var Float64Array: Float64ArrayConstructor;
/////////////////////////////
/// ECMAScript Internationalization API

lib/lib.esnext.bigint.d.ts

@@ -54,7 +54,7 @@
asUintN(bits: number, int: bigint): bigint;
}
-declare const BigInt: BigIntConstructor;
+declare var BigInt: BigIntConstructor;
/**
* A typed array of 64-bit signed integer values. The contents are initialized to 0. If the
@@ -323,7 +323,7 @@
from<U>(arrayLike: ArrayLike<U>, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigInt64Array;
}
-declare const BigInt64Array: BigInt64ArrayConstructor;
+declare var BigInt64Array: BigInt64ArrayConstructor;
/**
* A typed array of 64-bit unsigned integer values. The contents are initialized to 0. If the
@@ -592,7 +592,7 @@
from<U>(arrayLike: ArrayLike<U>, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigUint64Array;
}
-declare const BigUint64Array: BigUint64ArrayConstructor;
+declare var BigUint64Array: BigUint64ArrayConstructor;
interface DataView {
/**

lib/lib.esnext.d.ts

@@ -18,9 +18,6 @@
/// <reference no-default-lib="true"/>
-/// <reference lib="es2018" />
-/// <reference lib="esnext.asynciterable" />
-/// <reference lib="esnext.array" />
+/// <reference lib="es2019" />
/// <reference lib="esnext.bigint" />
-/// <reference lib="esnext.symbol" />
/// <reference lib="esnext.intl" />

lib/lib.webworker.d.ts

@@ -174,6 +174,10 @@
capture?: boolean;
}
+interface EventSourceInit {
+ withCredentials?: boolean;
+}
+
interface ExtendableEventInit extends EventInit {
}
@@ -475,6 +479,7 @@
(evt: Event): void;
}
+/** The ANGLE_instanced_arrays extension is part of the WebGL API and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type. */
interface ANGLE_instanced_arrays {
drawArraysInstancedANGLE(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei): void;
drawElementsInstancedANGLE(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, primcount: GLsizei): void;
@@ -482,6 +487,7 @@
readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: GLenum;
}
+/** The AbortController interface represents a controller object that allows you to abort one or more DOM requests as and when desired. */
interface AbortController {
/**
* Returns the AbortSignal object associated with this object.
@@ -500,16 +506,17 @@
};
interface AbortSignalEventMap {
- "abort": ProgressEvent;
+ "abort": Event;
}
+/** The AbortSignal interface represents a signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */
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;
+ onabort: ((this: AbortSignal, ev: Event) => any) | null;
addEventListener<K extends keyof AbortSignalEventMap>(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
removeEventListener<K extends keyof AbortSignalEventMap>(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
@@ -541,6 +548,7 @@
length: number;
}
+/** A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. */
interface Blob {
readonly size: number;
readonly type: string;
@@ -598,6 +606,7 @@
messageerror: MessageEvent;
}
+/** The ByteLengthQueuingStrategy interface of the the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. */
interface ByteLengthQueuingStrategy extends QueuingStrategy<ArrayBufferView> {
highWaterMark: number;
size(chunk: ArrayBufferView): number;
@@ -608,6 +617,7 @@
new(options: { highWaterMark: number }): ByteLengthQueuingStrategy;
};
+/** The Cache interface provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the ServiceWorker life cycle. Note that the Cache interface is exposed to windowed scopes as well as workers. You don't have to use it in conjunction with service workers, even though it is defined in the service worker spec. */
interface Cache {
add(request: RequestInfo): Promise<void>;
addAll(requests: RequestInfo[]): Promise<void>;
@@ -623,6 +633,7 @@
new(): Cache;
};
+/** The CacheStorage interface represents the storage for Cache objects. */
interface CacheStorage {
delete(cacheName: string): Promise<boolean>;
has(cacheName: string): Promise<boolean>;
@@ -636,6 +647,7 @@
new(): CacheStorage;
};
+/** The CanvasGradient interface represents an opaque object describing a gradient. It is returned by the methods CanvasRenderingContext2D.createLinearGradient() or CanvasRenderingContext2D.createRadialGradient(). */
interface CanvasGradient {
/**
* Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset
@@ -664,6 +676,7 @@
rect(x: number, y: number, w: number, h: number): void;
}
+/** The CanvasPattern interface represents an opaque object describing a pattern, based on an image, a canvas, or a video, created by the CanvasRenderingContext2D.createPattern() method. */
interface CanvasPattern {
/**
* Sets the transformation matrix that will be used when rendering the pattern during a fill or
@@ -677,6 +690,7 @@
new(): CanvasPattern;
};
+/** The Client interface represents an executable context such as a Worker, or a SharedWorker. Window clients are represented by the more-specific WindowClient. You can get Client/WindowClient objects from methods such as Clients.matchAll() and Clients.get(). */
interface Client {
readonly id: string;
readonly type: ClientTypes;
@@ -689,6 +703,7 @@
new(): Client;
};
+/** The Clients interface provides access to Client objects. Access it via self.clients within a service worker. */
interface Clients {
claim(): Promise<void>;
get(id: string): Promise<any>;
@@ -701,6 +716,7 @@
new(): Clients;
};
+/** A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute. */
interface CloseEvent extends Event {
readonly code: number;
readonly reason: string;
@@ -723,6 +739,7 @@
publicInfo?: Uint8Array;
}
+/** The Console object provides access to the browser's debugging console (e.g. the Web Console in Firefox). The specifics of how it works varies from browser to browser, but there is a de facto set of features that are typically provided. */
interface Console {
memory: any;
assert(condition?: boolean, message?: string, ...data: any[]): void;
@@ -756,6 +773,7 @@
new(): Console;
};
+/** The CountQueuingStrategy interface of the the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. */
interface CountQueuingStrategy extends QueuingStrategy {
highWaterMark: number;
size(chunk: any): 1;
@@ -766,6 +784,7 @@
new(options: { highWaterMark: number }): CountQueuingStrategy;
};
+/** The Crypto interface represents basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives. */
interface Crypto {
readonly subtle: SubtleCrypto;
getRandomValues<T extends Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null>(array: T): T;
@@ -776,6 +795,7 @@
new(): Crypto;
};
+/** The CryptoKey interface represents a cryptographic key derived from a specific key algorithm. */
interface CryptoKey {
readonly algorithm: KeyAlgorithm;
readonly extractable: boolean;
@@ -802,6 +822,7 @@
new<T>(typeArg: string, eventInitDict?: CustomEventInit<T>): CustomEvent<T>;
};
+/** The DOMException interface represents an abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. */
interface DOMException {
readonly code: number;
readonly message: string;
@@ -941,6 +962,8 @@
rotateFromVector(x?: number, y?: number): DOMMatrix;
scale(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;
scale3d(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;
+ /** @deprecated */
+ scaleNonUniform(scaleX?: number, scaleY?: number): DOMMatrix;
skewX(sx?: number): DOMMatrix;
skewY(sy?: number): DOMMatrix;
toFloat32Array(): Float32Array;
@@ -1033,6 +1056,7 @@
fromRect(other?: DOMRectInit): DOMRectReadOnly;
};
+/** A type returned by some APIs which contains a list of DOMString (strings). */
interface DOMStringList {
/**
* Returns the number of strings in strings.
@@ -1059,6 +1083,7 @@
"message": MessageEvent;
}
+/** The DedicatedWorkerGlobalScope object (the Worker global scope) is accessible through the self keyword. Some additional global functions, namespaces objects, and constructors, not typically associated with the worker global scope, but available on it, are listed in the JavaScript Reference. See also: Functions available to workers. */
interface DedicatedWorkerGlobalScope extends WorkerGlobalScope {
onmessage: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null;
close(): void;
@@ -1098,6 +1123,7 @@
readonly MIN_EXT: GLenum;
}
+/** The EXT_frag_depth extension is part of the WebGL API and enables to set a depth value of a fragment from within the fragment shader. */
interface EXT_frag_depth {
}
@@ -1111,11 +1137,13 @@
interface EXT_shader_texture_lod {
}
+/** The EXT_texture_filter_anisotropic extension is part of the WebGL API and exposes two constants for anisotropic filtering (AF). */
interface EXT_texture_filter_anisotropic {
readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: GLenum;
readonly TEXTURE_MAX_ANISOTROPY_EXT: GLenum;
}
+/** The ErrorEvent interface represents events providing information related to errors in scripts or in files. */
interface ErrorEvent extends Event {
readonly colno: number;
readonly error: any;
@@ -1129,6 +1157,7 @@
new(type: string, eventInitDict?: ErrorEventInit): ErrorEvent;
};
+/** The Event interface represents any event which takes place in the DOM; some are user-generated (such as mouse or keyboard events), while others are generated by APIs (such as events that indicate an animation has finished running, a video has been paused, and so forth). While events are usually triggered by such "external" sources, they can also be triggered programmatically, such as by calling the HTMLElement.click() method of an element, or by defining the event, then sending it to a specified target using EventTarget.dispatchEvent(). There are many types of events, some of which use other interfaces based on the main Event interface. Event itself contains the properties and methods which are common to all events. */
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.
@@ -1153,6 +1182,8 @@
*/
readonly isTrusted: boolean;
returnValue: boolean;
+ /** @deprecated */
+ readonly srcElement: EventTarget | null;
/**
* Returns the object to which event is dispatched (its target).
*/
@@ -1200,28 +1231,50 @@
handleEvent(evt: Event): void;
}
+interface EventSourceEventMap {
+ "error": Event;
+ "message": MessageEvent;
+ "open": Event;
+}
+
interface EventSource extends EventTarget {
- readonly CLOSED: number;
- readonly CONNECTING: number;
- readonly OPEN: number;
- onerror: (evt: MessageEvent) => any;
- onmessage: (evt: MessageEvent) => any;
- onopen: (evt: MessageEvent) => any;
+ onerror: ((this: EventSource, ev: Event) => any) | null;
+ onmessage: ((this: EventSource, ev: MessageEvent) => any) | null;
+ onopen: ((this: EventSource, ev: Event) => any) | null;
+ /**
+ * Returns the state of this EventSource object's connection. It can have the
+ * values described below.
+ */
readonly readyState: number;
+ /**
+ * Returns the URL providing the event stream.
+ */
readonly url: string;
+ /**
+ * Returns true if the credentials mode
+ * for connection requests to the URL providing the
+ * event stream is set to "include", and false otherwise.
+ */
readonly withCredentials: boolean;
close(): void;
+ readonly CLOSED: number;
+ readonly CONNECTING: number;
+ readonly OPEN: number;
+ addEventListener<K extends keyof EventSourceEventMap>(type: K, listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
+ removeEventListener<K extends keyof EventSourceEventMap>(type: K, listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}
declare var EventSource: {
prototype: EventSource;
new(url: string, eventSourceInitDict?: EventSourceInit): EventSource;
+ readonly CLOSED: number;
+ readonly CONNECTING: number;
+ readonly OPEN: number;
};
-interface EventSourceInit {
- readonly withCredentials: boolean;
-}
-
+/** EventTarget is an interface implemented by objects that can receive events and may have listeners for them. */
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.
@@ -1250,8 +1303,9 @@
new(): EventTarget;
};
+/** The ExtendableEvent interface extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries. */
interface ExtendableEvent extends Event {
- waitUntil(f: Promise<any>): void;
+ waitUntil(f: any): void;
}
declare var ExtendableEvent: {
@@ -1259,6 +1313,7 @@
new(type: string, eventInitDict?: ExtendableEventInit): ExtendableEvent;
};
+/** The ExtendableMessageEvent interface of the ServiceWorker API represents the event object of a message event fired on a service worker (when a channel message is received on the ServiceWorkerGlobalScope from another context) — extends the lifetime of such events. */
interface ExtendableMessageEvent extends ExtendableEvent {
readonly data: any;
readonly lastEventId: string;
@@ -1272,13 +1327,14 @@
new(type: string, eventInitDict?: ExtendableMessageEventInit): ExtendableMessageEvent;
};
+/** This is the event type for fetch events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith() method, which allows us to provide a response to this fetch. */
interface FetchEvent extends ExtendableEvent {
readonly clientId: string;
readonly preloadResponse: Promise<any>;
readonly request: Request;
readonly resultingClientId: string;
readonly targetClientId: string;
- respondWith(r: Promise<Response>): void;
+ respondWith(r: Response | Promise<Response>): void;
}
declare var FetchEvent: {
@@ -1286,6 +1342,7 @@
new(type: string, eventInitDict: FetchEventInit): FetchEvent;
};
+/** The File interface provides information about files and allows JavaScript in a web page to access their content. */
interface File extends Blob {
readonly lastModified: number;
readonly name: string;
@@ -1296,6 +1353,7 @@
new(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File;
};
+/** An object of this type is returned by the files property of the HTML <input> element; this lets you access the list of files selected with the <input type="file"> element. It's also used for a list of files dropped into web content when using the drag and drop API; see the DataTransfer object for details on this usage. */
interface FileList {
readonly length: number;
item(index: number): File | null;
@@ -1316,6 +1374,7 @@
"progress": ProgressEvent;
}
+/** The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. */
interface FileReader extends EventTarget {
readonly error: DOMException | null;
onabort: ((this: FileReader, ev: ProgressEvent) => any) | null;
@@ -1348,6 +1407,7 @@
readonly LOADING: number;
};
+/** The FileReaderSync interface allows to read File or Blob objects in a synchronous way. */
interface FileReaderSync {
readAsArrayBuffer(blob: Blob): ArrayBuffer;
readAsBinaryString(blob: Blob): string;
@@ -1360,6 +1420,7 @@
new(): FileReaderSync;
};
+/** The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data". */
interface FormData {
append(name: string, value: string | Blob, fileName?: string): void;
delete(name: string): void;
@@ -1379,6 +1440,7 @@
fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
}
+/** The Headers interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing. A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.  You can add to this using methods like append() (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence. */
interface Headers {
append(name: string, value: string): void;
delete(name: string): void;
@@ -1402,6 +1464,7 @@
interface IDBArrayKey extends Array<IDBValidKey> {
}
+/** The IDBCursor interface of the IndexedDB API represents a cursor for traversing or iterating over multiple records in a database. */
interface IDBCursor {
/**
* Returns the direction ("next", "nextunique", "prev" or "prevunique")
@@ -1412,12 +1475,12 @@
* Returns the key of the cursor.
* Throws a "InvalidStateError" DOMException if the cursor is advancing or is finished.
*/
- readonly key: IDBValidKey | IDBKeyRange;
+ readonly key: IDBValidKey;
/**
* Returns the effective key of the cursor.
* Throws a "InvalidStateError" DOMException if the cursor is advancing or is finished.
*/
- readonly primaryKey: IDBValidKey | IDBKeyRange;
+ readonly primaryKey: IDBValidKey;
/**
* Returns the IDBObjectStore or IDBIndex the cursor was opened from.
*/
@@ -1431,12 +1494,12 @@
* Advances the cursor to the next record in range matching or
* after key.
*/
- continue(key?: IDBValidKey | IDBKeyRange): void;
+ continue(key?: IDBValidKey): void;
/**
* Advances the cursor to the next record in range matching
* or after key and primaryKey. Throws an "InvalidAccessError" DOMException if the source is not an index.
*/
- continuePrimaryKey(key: IDBValidKey | IDBKeyRange, primaryKey: IDBValidKey | IDBKeyRange): void;
+ continuePrimaryKey(key: IDBValidKey, primaryKey: IDBValidKey): void;
/**
* Delete the record pointed at by the cursor with a new value.
* If successful, request's result will be undefined.
@@ -1455,6 +1518,7 @@
new(): IDBCursor;
};
+/** The IDBCursorWithValue interface of the IndexedDB API represents a cursor for traversing or iterating over multiple records in a database. It is the same as the IDBCursor, except that it includes the value property. */
interface IDBCursorWithValue extends IDBCursor {
/**
* Returns the cursor's current value.
@@ -1474,6 +1538,7 @@
"versionchange": IDBVersionChangeEvent;
}
+/** The IDBDatabase interface of the IndexedDB API provides a connection to a database; you can use an IDBDatabase object to open a transaction on your database then create, manipulate, and delete objects (data) in that database. The interface provides the only way to get and manage versions of the database. */
interface IDBDatabase extends EventTarget {
/**
* Returns the name of the database.
@@ -1521,6 +1586,7 @@
new(): IDBDatabase;
};
+/** In the following code snippet, we make a request to open a database, and include handlers for the success and error cases. For a full working example, see our To-do Notifications app (view example live.) */
interface IDBFactory {
/**
* Compares two values as keys. Returns -1 if key1 precedes key2, 1 if key2 precedes key1, and 0 if
@@ -1550,6 +1616,7 @@
new(): IDBFactory;
};
+/** IDBIndex interface of the IndexedDB API provides asynchronous access to an index in a database. An index is a kind of object store for looking up records in another object store, called the referenced object store. You use this interface to retrieve data. */
interface IDBIndex {
readonly keyPath: string | string[];
readonly multiEntry: boolean;
@@ -1610,6 +1677,7 @@
new(): IDBIndex;
};
+/** A key range can be a single value or a range with upper and lower bounds or endpoints. If the key range has both upper and lower bounds, then it is bounded; if it has no bounds, it is unbounded. A bounded key range can either be open (the endpoints are excluded) or closed (the endpoints are included). To retrieve all keys within a certain range, you can use the following code constructs: */
interface IDBKeyRange {
/**
* Returns lower bound, or undefined if none.
@@ -1658,6 +1726,7 @@
upperBound(upper: any, open?: boolean): IDBKeyRange;
};
+/** This example shows a variety of different uses of object stores, from updating the data structure with IDBObjectStore.createIndex inside an onupgradeneeded function, to adding a new item to our object store with IDBObjectStore.add. For a full working example, see our To-do Notifications app (view example live.) */
interface IDBObjectStore {
/**
* Returns true if the store has a key generator, and false otherwise.
@@ -1681,7 +1750,7 @@
* Returns the associated transaction.
*/
readonly transaction: IDBTransaction;
- add(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest<IDBValidKey>;
+ add(value: any, key?: IDBValidKey): IDBRequest<IDBValidKey>;
/**
* Deletes all records in store.
* If successful, request's result will
@@ -1754,7 +1823,7 @@
* null if there were no matching records.
*/
openKeyCursor(query?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest<IDBCursor | null>;
- put(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest<IDBValidKey>;
+ put(value: any, key?: IDBValidKey): IDBRequest<IDBValidKey>;
}
declare var IDBObjectStore: {
@@ -1767,6 +1836,7 @@
"upgradeneeded": IDBVersionChangeEvent;
}
+/** Also inherits methods from its parents IDBRequest and EventTarget. */
interface IDBOpenDBRequest extends IDBRequest<IDBDatabase> {
onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null;
onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null;
@@ -1786,6 +1856,7 @@
"success": Event;
}
+/** The request object does not initially contain any information about the result of the operation, but once information becomes available, an event is fired on the request, and the information becomes available through the properties of the IDBRequest instance. */
interface IDBRequest<T = any> extends EventTarget {
/**
* When a request is completed, returns the error (a DOMException), or null if the request succeeded. Throws
@@ -1877,6 +1948,7 @@
new(): IDBTransaction;
};
+/** The IDBVersionChangeEvent interface of the IndexedDB API indicates that the version of the database has changed, as the result of an IDBOpenDBRequest.onupgradeneeded event handler function. */
interface IDBVersionChangeEvent extends Event {
readonly newVersion: number | null;
readonly oldVersion: number;
@@ -1918,6 +1990,7 @@
resizeWidth?: number;
}
+/** The ImageData interface represents the underlying pixel data of an area of a <canvas> element. It is created using the ImageData() constructor or creator methods on the CanvasRenderingContext2D object associated with a canvas: createImageData() and getImageData(). It can also be used to set a part of the canvas by using putImageData(). */
interface ImageData {
/**
* Returns the one-dimensional array containing the data in RGBA order, as integers in the
@@ -1938,6 +2011,7 @@
new(array: Uint8ClampedArray, width: number, height: number): ImageData;
};
+/** The MessageChannel interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. */
interface MessageChannel {
readonly port1: MessagePort;
readonly port2: MessagePort;
@@ -1948,6 +2022,7 @@
new(): MessageChannel;
};
+/** The MessageEvent interface represents a message received by a target object. */
interface MessageEvent extends Event {
/**
* Returns the data of the message.
@@ -1986,6 +2061,7 @@
"messageerror": MessageEvent;
}
+/** The MessagePort interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. */
interface MessagePort extends EventTarget {
onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null;
onmessageerror: ((this: MessagePort, ev: MessageEvent) => any) | null;
@@ -2063,6 +2139,7 @@
"show": Event;
}
+/** The Notification interface of the Notifications API is used to configure and display desktop notifications to the user. */
interface Notification extends EventTarget {
readonly actions: ReadonlyArray<NotificationAction>;
readonly badge: string;
@@ -2097,6 +2174,7 @@
readonly permission: NotificationPermission;
};
+/** The parameter passed into the onnotificationclick handler, the NotificationEvent interface represents a notification click event that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker. */
interface NotificationEvent extends ExtendableEvent {
readonly action: string;
readonly notification: Notification;
@@ -2107,23 +2185,29 @@
new(type: string, eventInitDict: NotificationEventInit): NotificationEvent;
};
+/** The OES_element_index_uint extension is part of the WebGL API and adds support for gl.UNSIGNED_INT types to WebGLRenderingContext.drawElements(). */
interface OES_element_index_uint {
}
+/** The OES_standard_derivatives extension is part of the WebGL API and adds the GLSL derivative functions dFdx, dFdy, and fwidth. */
interface OES_standard_derivatives {
readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: GLenum;
}
+/** The OES_texture_float extension is part of the WebGL API and exposes floating-point pixel types for textures. */
interface OES_texture_float {
}
+/** The OES_texture_float_linear extension is part of the WebGL API and allows linear filtering with floating-point pixel types for textures. */
interface OES_texture_float_linear {
}
+/** The OES_texture_half_float extension is part of the WebGL API and adds texture formats with 16- (aka half float) and 32-bit floating-point components. */
interface OES_texture_half_float {
readonly HALF_FLOAT_OES: GLenum;
}
+/** The OES_texture_half_float_linear extension is part of the WebGL API and allows linear filtering with half floating-point pixel types for textures. */
interface OES_texture_half_float_linear {
}
@@ -2135,6 +2219,7 @@
readonly VERTEX_ARRAY_BINDING_OES: GLenum;
}
+/** The Path2D interface of the Canvas 2D API is used to declare a path that can then be used on a CanvasRenderingContext2D object. The path methods of the CanvasRenderingContext2D interface are also present on this interface, which gives you the convenience of being able to retain and replay your path whenever desired. */
interface Path2D extends CanvasPath {
addPath(path: Path2D, transform?: DOMMatrix2DInit): void;
}
@@ -2148,6 +2233,7 @@
"resourcetimingbufferfull": Event;
}
+/** The Performance interface provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */
interface Performance extends EventTarget {
onresourcetimingbufferfull: ((this: Performance, ev: Event) => any) | null;
readonly timeOrigin: number;
@@ -2173,6 +2259,7 @@
new(): Performance;
};
+/** The PerformanceEntry object encapsulates a single performance metric that is part of the performance timeline. A performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application. Performance entries are also created in indirect ways such as loading a resource (such as an image). */
interface PerformanceEntry {
readonly duration: number;
readonly entryType: string;
@@ -2186,6 +2273,7 @@
new(): PerformanceEntry;
};
+/** PerformanceMark is an abstract interface for PerformanceEntry objects with an entryType of "mark". Entries of this type are created by calling performance.mark() to add a named DOMHighResTimeStamp (the mark) to the browser's performance timeline. */
interface PerformanceMark extends PerformanceEntry {
}
@@ -2194,6 +2282,7 @@
new(): PerformanceMark;
};
+/** PerformanceMeasure is an abstract interface for PerformanceEntry objects with an entryType of "measure". Entries of this type are created by calling performance.measure() to add a named DOMHighResTimeStamp (the measure) between two marks to the browser's performance timeline. */
interface PerformanceMeasure extends PerformanceEntry {
}
@@ -2224,6 +2313,7 @@
new(): PerformanceObserverEntryList;
};
+/** The PerformanceResourceTiming interface enables retrieval and analysis of detailed network timing data regarding the loading of an application's resources. An application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource, such as an XMLHttpRequest, <SVG>, image, or script. */
interface PerformanceResourceTiming extends PerformanceEntry {
readonly connectEnd: number;
readonly connectStart: number;
@@ -2250,6 +2340,7 @@
new(): PerformanceResourceTiming;
};
+/** The ProgressEvent interface represents events measuring progress of an underlying process, like an HTTP request (for an XMLHttpRequest, or the loading of the underlying resource of an <img>, <audio>, <video>, <style> or <link>). */
interface ProgressEvent extends Event {
readonly lengthComputable: boolean;
readonly loaded: number;
@@ -2271,6 +2362,7 @@
new(type: string, eventInitDict: PromiseRejectionEventInit): PromiseRejectionEvent;
};
+/** The PushEvent interface of the Push API represents a push message that has been received. This event is sent to the global scope of a ServiceWorker. It contains the information sent from an application server to a PushSubscription. */
interface PushEvent extends ExtendableEvent {
readonly data: PushMessageData | null;
}
@@ -2280,6 +2372,7 @@
new(type: string, eventInitDict?: PushEventInit): PushEvent;
};
+/** The PushManager interface of the Push API provides a way to receive notifications from third-party servers as well as request URLs for push notifications. */
interface PushManager {
getSubscription(): Promise<PushSubscription | null>;
permissionState(options?: PushSubscriptionOptionsInit): Promise<PushPermissionState>;
@@ -2292,6 +2385,7 @@
readonly supportedContentEncodings: ReadonlyArray<string>;
};
+/** The PushMessageData interface of the Push API provides methods which let you retrieve the push data sent by a server in various formats. */
interface PushMessageData {
arrayBuffer(): ArrayBuffer;
blob(): Blob;
@@ -2304,6 +2398,7 @@
new(): PushMessageData;
};
+/** The PushSubscription interface of the Push API provides a subcription's URL endpoint and allows unsubscription from a push service. */
interface PushSubscription {
readonly endpoint: string;
readonly expirationTime: number | null;
@@ -2346,6 +2441,7 @@
error(error?: any): void;
}
+/** The ReadableStream interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. */
interface ReadableStream<R = any> {
readonly locked: boolean;
cancel(reason?: any): Promise<void>;
@@ -2410,6 +2506,7 @@
new(): ReadableStreamReader;
};
+/** The Request interface of the Fetch API represents a resource request. */
interface Request extends Body {
/**
* Returns the cache mode associated with request, which is a string indicating
@@ -2495,6 +2592,7 @@
new(input: RequestInfo, init?: RequestInit): Request;
};
+/** The Response interface of the Fetch API represents the response to a request. */
interface Response extends Body {
readonly headers: Headers;
readonly ok: boolean;
@@ -2518,6 +2616,7 @@
"statechange": Event;
}
+/** The ServiceWorker interface of the ServiceWorker API provides a reference to a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same service worker, each through a unique ServiceWorker object. */
interface ServiceWorker extends EventTarget, AbstractWorker {
onstatechange: ((this: ServiceWorker, ev: Event) => any) | null;
readonly scriptURL: string;
@@ -2540,6 +2639,7 @@
"messageerror": MessageEvent;
}
+/** The ServiceWorkerContainer interface of the ServiceWorker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations. */
interface ServiceWorkerContainer extends EventTarget {
readonly controller: ServiceWorker | null;
oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null;
@@ -2574,6 +2674,7 @@
"sync": SyncEvent;
}
+/** The ServiceWorkerGlobalScope interface of the ServiceWorker API represents the global execution context of a service worker. */
interface ServiceWorkerGlobalScope extends WorkerGlobalScope {
readonly clients: Clients;
onactivate: ((this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any) | null;
@@ -2603,6 +2704,7 @@
"updatefound": Event;
}
+/** The ServiceWorkerRegistration interface of the ServiceWorker API represents the service worker registration. You register a service worker to control one or more pages that share the same origin. */
interface ServiceWorkerRegistration extends EventTarget {
readonly active: ServiceWorker | null;
readonly installing: ServiceWorker | null;
@@ -2638,6 +2740,7 @@
new(): StorageManager;
};
+/** The SubtleCrypto interface represents a set of cryptographic primitives. It is available via the Crypto.subtle properties available in a window context (via Window.crypto). */
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<ArrayBuffer>;
deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike<ArrayBuffer>;
@@ -2664,6 +2767,7 @@
new(): SubtleCrypto;
};
+/** The SyncEvent interface represents a sync action that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker.  */
interface SyncEvent extends ExtendableEvent {
readonly lastChance: boolean;
readonly tag: string;
@@ -2674,6 +2778,7 @@
new(type: string, init: SyncEventInit): SyncEvent;
};
+/** The SyncManager interface of the the ServiceWorker API provides an interface for registering and listing sync registrations. */
interface SyncManager {
getTags(): Promise<string[]>;
register(tag: string): Promise<void>;
@@ -2684,6 +2789,7 @@
new(): SyncManager;
};
+/** The TextDecoder interface represents a decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, etc. A decoder takes a stream of bytes as input and emits a stream of code points. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. */
interface TextDecoder {
/**
* Returns encoding's name, lowercased.
@@ -2719,6 +2825,7 @@
new(label?: string, options?: TextDecoderOptions): TextDecoder;
};
+/** TextEncoder takes a stream of code points as input and emits a stream of bytes. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. */
interface TextEncoder {
/**
* Returns "utf-8".
@@ -2735,6 +2842,7 @@
new(): TextEncoder;
};
+/** The TextMetrics interface represents the dimension of a text in the canvas, as created by the CanvasRenderingContext2D.measureText() method. */
interface TextMetrics {
readonly actualBoundingBoxAscent: number;
readonly actualBoundingBoxDescent: number;
@@ -2775,6 +2883,7 @@
terminate(): void;
}
+/** The URL interface represents an object providing static methods used for creating object URLs. */
interface URL {
hash: string;
host: string;
@@ -2870,6 +2979,7 @@
readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: GLenum;
}
+/** The WEBGL_compressed_texture_s3tc extension is part of the WebGL API and exposes four S3TC compressed texture formats. */
interface WEBGL_compressed_texture_s3tc {
readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: GLenum;
readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: GLenum;
@@ -2884,6 +2994,7 @@
readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: GLenum;
}
+/** The WEBGL_debug_renderer_info extension is part of the WebGL API and exposes two constants with information about the graphics driver for debugging purposes. */
interface WEBGL_debug_renderer_info {
readonly UNMASKED_RENDERER_WEBGL: GLenum;
readonly UNMASKED_VENDOR_WEBGL: GLenum;
@@ -2893,6 +3004,7 @@
getTranslatedShaderSource(shader: WebGLShader): string;
}
+/** The WEBGL_depth_texture extension is part of the WebGL API and defines 2D depth and depth-stencil textures. */
interface WEBGL_depth_texture {
readonly UNSIGNED_INT_24_8_WEBGL: GLenum;
}
@@ -2940,6 +3052,7 @@
restoreContext(): void;
}
+/** The WebGLActiveInfo interface is part of the WebGL API and represents the information returned by calling the WebGLRenderingContext.getActiveAttrib() and WebGLRenderingContext.getActiveUniform() methods. */
interface WebGLActiveInfo {
readonly name: string;
readonly size: GLint;
@@ -2951,6 +3064,7 @@
new(): WebGLActiveInfo;
};
+/** The WebGLBuffer interface is part of the WebGL API and represents an opaque buffer object storing data such as vertices or colors. */
interface WebGLBuffer extends WebGLObject {
}
@@ -2959,6 +3073,7 @@
new(): WebGLBuffer;
};
+/** The WebContextEvent interface is part of the WebGL API and is an interface for an event that is generated in response to a status change to the WebGL rendering context. */
interface WebGLContextEvent extends Event {
readonly statusMessage: string;
}
@@ -2968,6 +3083,7 @@
new(type: string, eventInit?: WebGLContextEventInit): WebGLContextEvent;
};
+/** The WebGLFramebuffer interface is part of the WebGL API and represents a collection of buffers that serve as a rendering destination. */
interface WebGLFramebuffer extends WebGLObject {
}
@@ -2984,6 +3100,7 @@
new(): WebGLObject;
};
+/** The WebGLProgram is part of the WebGL API and is a combination of two compiled WebGLShaders consisting of a vertex shader and a fragment shader (both written in GLSL). */
interface WebGLProgram extends WebGLObject {
}
@@ -2992,6 +3109,7 @@
new(): WebGLProgram;
};
+/** The WebGLRenderbuffer interface is part of the WebGL API and represents a buffer that can contain an image, or can be source or target of an rendering operation. */
interface WebGLRenderbuffer extends WebGLObject {
}
@@ -3000,6 +3118,7 @@
new(): WebGLRenderbuffer;
};
+/** The WebGLRenderingContext interface provides an interface to the OpenGL ES 2.0 graphics rendering context for the drawing surface of an HTML <canvas> element. */
interface WebGLRenderingContext extends WebGLRenderingContextBase {
}
@@ -3418,7 +3537,7 @@
isTexture(texture: WebGLTexture | null): GLboolean;
lineWidth(width: GLfloat): void;
linkProgram(program: WebGLProgram): void;
- pixelStorei(pname: GLenum, param: GLint): void;
+ pixelStorei(pname: GLenum, param: GLint | GLboolean): 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;
@@ -3766,6 +3885,7 @@
readonly ZERO: GLenum;
}
+/** The WebGLShader is part of the WebGL API and can either be a vertex or a fragment shader. A WebGLProgram requires both types of shaders. */
interface WebGLShader extends WebGLObject {
}
@@ -3774,6 +3894,7 @@
new(): WebGLShader;
};
+/** The WebGLShaderPrecisionFormat interface is part of the WebGL API and represents the information returned by calling the WebGLRenderingContext.getShaderPrecisionFormat() method. */
interface WebGLShaderPrecisionFormat {
readonly precision: GLint;
readonly rangeMax: GLint;
@@ -3785,6 +3906,7 @@
new(): WebGLShaderPrecisionFormat;
};
+/** The WebGLTexture interface is part of the WebGL API and represents an opaque texture object providing storage and state for texturing operations. */
interface WebGLTexture extends WebGLObject {
}
@@ -3793,6 +3915,7 @@
new(): WebGLTexture;
};
+/** The WebGLUniformLocation interface is part of the WebGL API and represents the location of a uniform variable in a shader program. */
interface WebGLUniformLocation {
}
@@ -3811,6 +3934,7 @@
"open": Event;
}
+/** The WebSocket object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. */
interface WebSocket extends EventTarget {
binaryType: BinaryType;
readonly bufferedAmount: number;
@@ -3848,6 +3972,7 @@
btoa(rawString: string): string;
}
+/** The WindowClient interface of the ServiceWorker API represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. The service worker client independently selects and uses a service worker for its own loading and sub-resources. */
interface WindowClient extends Client {
readonly ancestorOrigins: ReadonlyArray<string>;
readonly focused: boolean;
@@ -3887,6 +4012,7 @@
"message": MessageEvent;
}
+/** The Worker interface of the Web Workers API represents a background task that can be easily created and can send messages back to its creator. Creating a worker is as simple as calling the Worker() constructor and specifying a script to be run in the worker thread. */
interface Worker extends EventTarget, AbstractWorker {
onmessage: ((this: Worker, ev: MessageEvent) => any) | null;
postMessage(message: any, transfer?: Transferable[]): void;
@@ -3899,13 +4025,14 @@
declare var Worker: {
prototype: Worker;
- new(stringUrl: string, options?: WorkerOptions): Worker;
+ new(stringUrl: string | URL, options?: WorkerOptions): Worker;
};
interface WorkerGlobalScopeEventMap {
"error": ErrorEvent;
}
+/** The WorkerGlobalScope interface of the Web Workers API is an interface representing the scope of any worker. Workers have no browsing context; this scope contains the information usually conveyed by Window objects — in this case event handlers, the console or the associated WorkerNavigator object. Each WorkerGlobalScope has its own event loop. */
interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, GlobalFetch, WindowOrWorkerGlobalScope {
readonly caches: CacheStorage;
readonly isSecureContext: boolean;
@@ -3925,6 +4052,7 @@
new(): WorkerGlobalScope;
};
+/** The WorkerLocation interface defines the absolute location of the script executed by the Worker. Such an object is initialized for each worker and is available via the WorkerGlobalScope.location property obtained by calling self.location. */
interface WorkerLocation {
readonly hash: string;
readonly host: string;
@@ -3943,6 +4071,7 @@
new(): WorkerLocation;
};
+/** The WorkerNavigator interface represents a subset of the Navigator interface allowed to be accessed from a Worker. Such an object is initialized for each worker and is available via the WorkerGlobalScope.navigator property obtained by calling window.self.navigator. */
interface WorkerNavigator extends NavigatorID, NavigatorOnLine, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorStorage {
readonly serviceWorker: ServiceWorkerContainer;
}
@@ -3959,6 +4088,7 @@
importScripts(...urls: string[]): void;
}
+/** The WritableStream interface of the the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing. */
interface WritableStream<W = any> {
readonly locked: boolean;
abort(reason?: any): Promise<void>;
@@ -3970,10 +4100,12 @@
new<W = any>(underlyingSink?: UnderlyingSink<W>, strategy?: QueuingStrategy<W>): WritableStream<W>;
};
+/** The WritableStreamDefaultController interface of the the Streams API represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate. */
interface WritableStreamDefaultController {
error(error?: any): void;
}
+/** The WritableStreamDefaultWriter interface of the the Streams API is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink. */
interface WritableStreamDefaultWriter<W = any> {
readonly closed: Promise<void>;
readonly desiredSize: number | null;
@@ -3988,6 +4120,7 @@
"readystatechange": Event;
}
+/** Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. */
interface XMLHttpRequest extends XMLHttpRequestEventTarget {
onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null;
/**
@@ -4062,7 +4195,8 @@
*/
overrideMimeType(mime: string): void;
/**
- * Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD.
+ * Initiates the request. The body argument provides the request body, if any,
+ * and is ignored if the request method is GET or HEAD.
* Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set.
*/
send(body?: BodyInit | null): void;
@@ -4279,7 +4413,7 @@
type NotificationPermission = "default" | "denied" | "granted";
type PushEncryptionKeyName = "p256dh" | "auth";
type PushPermissionState = "denied" | "granted" | "prompt";
-type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url";
+type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached";
type RequestCredentials = "omit" | "same-origin" | "include";
type RequestDestination = "" | "audio" | "audioworklet" | "document" | "embed" | "font" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt";

lib/protocol.d.ts

@@ -49,6 +49,7 @@
OpenExternalProject = "openExternalProject",
OpenExternalProjects = "openExternalProjects",
CloseExternalProject = "closeExternalProject",
+ UpdateOpen = "updateOpen",
GetOutliningSpans = "getOutliningSpans",
TodoComments = "todoComments",
Indentation = "indentation",
@@ -1023,6 +1024,8 @@
command: CommandTypes.ConfigurePlugin;
arguments: ConfigurePluginRequestArguments;
}
+ interface ConfigurePluginResponse extends Response {
+ }
/**
* Information found in an "open" request.
*/
@@ -1118,6 +1121,30 @@
interface CloseExternalProjectResponse extends Response {
}
/**
+ * Request to synchronize list of open files with the client
+ */
+ interface UpdateOpenRequest extends Request {
+ command: CommandTypes.UpdateOpen;
+ arguments: UpdateOpenRequestArgs;
+ }
+ /**
+ * Arguments to UpdateOpenRequest
+ */
+ interface UpdateOpenRequestArgs {
+ /**
+ * List of newly open files
+ */
+ openFiles?: OpenRequestArgs[];
+ /**
+ * List of open files files that were changes
+ */
+ changedFiles?: FileCodeEdits[];
+ /**
+ * List of files that were closed
+ */
+ 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.

lib/README.md

@@ -2,4 +2,4 @@
**These files are not meant to be edited by hand.**
If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory.
-Running `jake LKG` will then appropriately update the files in this directory.
+Running `gulp LKG` will then appropriately update the files in this directory.

lib/tsc.js

@@ -15,7 +15,6 @@
"use strict";
-"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
@@ -60,8 +59,8 @@
};
var ts;
(function (ts) {
- ts.versionMajorMinor = "3.3";
- ts.version = ts.versionMajorMinor + ".4000";
+ ts.versionMajorMinor = "3.4";
+ ts.version = ts.versionMajorMinor + ".5";
})(ts || (ts = {}));
(function (ts) {
ts.emptyArray = [];
@@ -97,19 +96,24 @@
ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap();
function shimMap() {
var MapIterator = (function () {
- function MapIterator(data, selector) {
- this.index = 0;
- this.data = data;
+ function MapIterator(currentEntry, selector) {
+ this.currentEntry = currentEntry;
this.selector = selector;
- this.keys = Object.keys(data);
}
MapIterator.prototype.next = function () {
- var index = this.index;
- if (index < this.keys.length) {
- this.index++;
- return { value: this.selector(this.data, this.keys[index]), done: false };
+ while (this.currentEntry) {
+ var skipNext = !!this.currentEntry.skipNext;
+ this.currentEntry = this.currentEntry.nextEntry;
+ if (!skipNext) {
+ break;
+ }
+ }
+ if (this.currentEntry) {
+ return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false };
}
+ else {
return { value: undefined, done: true };
+ }
};
return MapIterator;
}());
@@ -117,15 +121,29 @@
function class_1() {
this.data = createDictionaryObject();
this.size = 0;
+ this.firstEntry = {};
+ this.lastEntry = this.firstEntry;
}
class_1.prototype.get = function (key) {
- return this.data[key];
+ var entry = this.data[key];
+ return entry && entry.value;
};
class_1.prototype.set = function (key, value) {
if (!this.has(key)) {
this.size++;
+ var newEntry = {
+ key: key,
+ value: value
+ };
+ this.data[key] = newEntry;
+ var previousLastEntry = this.lastEntry;
+ previousLastEntry.nextEntry = newEntry;
+ newEntry.previousEntry = previousLastEntry;
+ this.lastEntry = newEntry;
+ }
+ else {
+ this.data[key].value = value;
}
- this.data[key] = value;
return this;
};
class_1.prototype.has = function (key) {
@@ -134,7 +152,19 @@
class_1.prototype.delete = function (key) {
if (this.has(key)) {
this.size--;
+ var entry = this.data[key];
delete this.data[key];
+ var previousEntry = entry.previousEntry;
+ previousEntry.nextEntry = entry.nextEntry;
+ if (entry.nextEntry) {
+ entry.nextEntry.previousEntry = previousEntry;
+ }
+ if (this.lastEntry === entry) {
+ this.lastEntry = previousEntry;
+ }
+ entry.previousEntry = undefined;
+ entry.nextEntry = previousEntry;
+ entry.skipNext = true;
return true;
}
return false;
@@ -142,24 +172,41 @@
class_1.prototype.clear = function () {
this.data = createDictionaryObject();
this.size = 0;
+ var firstEntry = this.firstEntry;
+ var currentEntry = firstEntry.nextEntry;
+ while (currentEntry) {
+ var nextEntry = currentEntry.nextEntry;
+ currentEntry.previousEntry = undefined;
+ currentEntry.nextEntry = firstEntry;
+ currentEntry.skipNext = true;
+ currentEntry = nextEntry;
+ }
+ firstEntry.nextEntry = undefined;
+ this.lastEntry = firstEntry;
};
class_1.prototype.keys = function () {
- return new MapIterator(this.data, function (_data, key) { return key; });
+ return new MapIterator(this.firstEntry, function (key) { return key; });
};
class_1.prototype.values = function () {
- return new MapIterator(this.data, function (data, key) { return data[key]; });
+ return new MapIterator(this.firstEntry, function (_key, value) { return value; });
};
class_1.prototype.entries = function () {
- return new MapIterator(this.data, function (data, key) { return [key, data[key]]; });
+ return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; });
};
class_1.prototype.forEach = function (action) {
- for (var key in this.data) {
- action(this.data[key], key);
+ var iterator = this.entries();
+ while (true) {
+ var _a = iterator.next(), entry = _a.value, done = _a.done;
+ if (done) {
+ break;
+ }
+ action(entry[1], entry[0]);
}
};
return class_1;
}());
}
+ ts.shimMap = shimMap;
function length(array) {
return array ? array.length : 0;
}
@@ -855,6 +902,21 @@
} };
}
ts.arrayIterator = arrayIterator;
+ function arrayReverseIterator(array) {
+ var i = array.length;
+ return {
+ next: function () {
+ if (i === 0) {
+ return { value: undefined, done: true };
+ }
+ else {
+ i--;
+ return { value: array[i], done: false };
+ }
+ }
+ };
+ }
+ ts.arrayReverseIterator = arrayReverseIterator;
function stableSort(array, comparer) {
var indices = array.map(function (_, i) { return i; });
stableSortIndices(array, indices, comparer);
@@ -1013,6 +1075,8 @@
}
for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
var arg = args_1[_a];
+ if (arg === undefined)
+ continue;
for (var p in arg) {
if (hasProperty(arg, p)) {
t[p] = arg[p];
@@ -1176,6 +1240,8 @@
ts.returnFalse = returnFalse;
function returnTrue() { return true; }
ts.returnTrue = returnTrue;
+ function returnUndefined() { return undefined; }
+ ts.returnUndefined = returnUndefined;
function identity(x) { return x; }
ts.identity = identity;
function toLowerCase(x) { return x.toLowerCase(); }
@@ -1312,7 +1378,7 @@
Debug.assertEachDefined = assertEachDefined;
function assertNever(member, message, stackCrawlMark) {
if (message === void 0) { message = "Illegal value:"; }
- var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member);
+ var detail = typeof member === "object" && "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member);
return fail(message + " " + detail, stackCrawlMark || assertNever);
}
Debug.assertNever = assertNever;
@@ -2177,8 +2243,11 @@
var ts;
(function (ts) {
function generateDjb2Hash(data) {
- var chars = data.split("").map(function (str) { return str.charCodeAt(0); });
- return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381);
+ var acc = 5381;
+ for (var i = 0; i < data.length; i++) {
+ acc = ((acc << 5) + acc) + data.charCodeAt(i);
+ }
+ return acc.toString();
}
ts.generateDjb2Hash = generateDjb2Hash;
function setStackTraceLimit() {
@@ -2408,6 +2477,7 @@
: FileWatcherEventKind.Changed;
}
ts.getFileWatcherEventKind = getFileWatcherEventKind;
+ ts.ignoredPaths = ["/node_modules/.", "/.git"];
function createRecursiveDirectoryWatcher(host) {
var cache = ts.createMap();
var callbackCache = ts.createMultiMap();
@@ -2423,6 +2493,8 @@
else {
directoryWatcher = {
watcher: host.watchDirectory(dirName, function (fileName) {
+ if (isIgnoredPath(fileName))
+ return;
callbackCache.forEach(function (callbacks, rootDirName) {
if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
callbacks.forEach(function (callback) { return callback(fileName); });
@@ -2464,7 +2536,7 @@
var newChildWatches;
ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
- return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 ? childFullName : undefined;
+ return !isIgnoredPath(childFullName) && 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) {
@@ -2475,6 +2547,16 @@
(newChildWatches || (newChildWatches = [])).push(childWatcher);
}
}
+ function isIgnoredPath(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
+ }
+ function isInPath(path, searchPath) {
+ if (ts.stringContains(path, searchPath))
+ return true;
+ if (host.useCaseSensitiveFileNames)
+ return false;
+ return ts.stringContains(toCanonicalFilePath(path), searchPath);
+ }
}
ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher;
function getNodeMajorVersion() {
@@ -2533,8 +2615,15 @@
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!nodeSystem.directoryExists(directoryName)) {
+ try {
_fs.mkdirSync(directoryName);
}
+ catch (e) {
+ if (e.code !== "EEXIST") {
+ throw e;
+ }
+ }
+ }
},
getExecutingFilePath: function () {
return __filename;
@@ -2550,7 +2639,7 @@
getModifiedTime: getModifiedTime,
setModifiedTime: setModifiedTime,
deleteFile: deleteFile,
- createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash,
+ createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
createSHA256Hash: _crypto ? createSHA256Hash : undefined,
getMemoryUsage: function () {
if (global.gc) {
@@ -2875,7 +2964,7 @@
}
}
function readDirectory(path, extensions, excludes, includes, depth) {
- return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries);
+ return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
}
function fileSystemEntryExists(path, entryKind) {
try {
@@ -2931,11 +3020,6 @@
return;
}
}
- function createMD5HashUsingNativeCrypto(data) {
- var hash = _crypto.createHash("md5");
- hash.update(data);
- return hash.digest("hex");
- }
function createSHA256Hash(data) {
var hash = _crypto.createHash("sha256");
hash.update(data);
@@ -3187,7 +3271,6 @@
Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."),
Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."),
- Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."),
Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."),
A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."),
Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."),
@@ -3278,6 +3361,8 @@
An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."),
A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."),
A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."),
+ readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types: diag(1354, ts.DiagnosticCategory.Error, "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354", "'readonly' type modifier is only permitted on array and tuple literal types."),
+ A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal: diag(1355, ts.DiagnosticCategory.Error, "A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal_1355", "A 'const' assertion can only be applied to a string, number, boolean, array, or object literal."),
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."),
@@ -3372,7 +3457,7 @@
Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."),
Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
- Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."),
+ This_overload_signature_is_not_compatible_with_its_implementation_signature: diag(2394, ts.DiagnosticCategory.Error, "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394", "This overload signature is not compatible with its implementation signature."),
Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."),
Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."),
Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."),
@@ -3545,15 +3630,20 @@
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."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."),
Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."),
_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
+ Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."),
+ Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
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."),
@@ -3660,6 +3750,12 @@
This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."),
This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."),
_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."),
+ Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided: diag(2748, ts.DiagnosticCategory.Error, "Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided_2748", "Cannot access ambient const enums when the '--isolatedModules' flag is provided."),
+ _0_refers_to_a_value_but_is_being_used_as_a_type_here: diag(2749, ts.DiagnosticCategory.Error, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_2749", "'{0}' refers to a value, but is being used as a type here."),
+ The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
+ Circularity_originates_in_type_at_this_location: diag(2751, ts.DiagnosticCategory.Error, "Circularity_originates_in_type_at_this_location_2751", "Circularity originates in type at this location."),
+ The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
+ Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
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}'."),
@@ -3743,6 +3839,7 @@
Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
@@ -3791,7 +3888,7 @@
Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."),
Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
- Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."),
+ Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'."),
Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."),
Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
@@ -4010,6 +4107,16 @@
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."),
Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
+ Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
+ Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
+ A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
+ A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
+ Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
+ Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
+ Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
+ Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
+ Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
+ Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
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."),
The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
@@ -4046,7 +4153,7 @@
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'."),
+ The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."),
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."),
Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
@@ -4226,6 +4333,7 @@
Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
+ Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
};
})(ts || (ts = {}));
var ts;
@@ -4624,19 +4732,28 @@
ts.Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
+ ts.isShebangTrivia = isShebangTrivia;
function scanShebangTrivia(text, pos) {
var shebang = shebangTriviaRegex.exec(text)[0];
pos = pos + shebang.length;
return pos;
}
+ ts.scanShebangTrivia = scanShebangTrivia;
function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
var pendingPos;
var pendingEnd;
var pendingKind;
var pendingHasTrailingNewLine;
var hasPendingCommentRange = false;
- var collecting = trailing || pos === 0;
+ var collecting = trailing;
var accumulator = initial;
+ if (pos === 0) {
+ collecting = true;
+ var shebang = getShebang(text);
+ if (shebang) {
+ pos = shebang.length;
+ }
+ }
scan: while (pos >= 0 && pos < text.length) {
var ch = text.charCodeAt(pos);
switch (ch) {
@@ -5798,6 +5915,7 @@
}
pos++;
}
+ tokenValue = text.substring(startPos, pos);
return firstNonWhitespace === -1 ? 12 : 11;
}
function scanJsxIdentifier() {
@@ -5876,8 +5994,8 @@
pos++;
return token = 14;
}
- if (isIdentifierStart(ch, 6)) {
- while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) {
+ if (isIdentifierStart(ch, 7)) {
+ while (isIdentifierPart(text.charCodeAt(pos), 7) && pos < end) {
pos++;
}
tokenValue = text.substring(tokenPos, pos);
@@ -6218,7 +6336,7 @@
}
}
function getSourceFileOfNode(node) {
- while (node && node.kind !== 279) {
+ while (node && node.kind !== 284) {
node = node.parent;
}
return node;
@@ -6281,7 +6399,7 @@
return !nodeIsMissing(node);
}
ts.nodeIsPresent = nodeIsPresent;
- function addStatementsAfterPrologue(to, from) {
+ function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
if (from === undefined || from.length === 0)
return to;
var statementIndex = 0;
@@ -6293,7 +6411,37 @@
to.splice.apply(to, [statementIndex, 0].concat(from));
return to;
}
- ts.addStatementsAfterPrologue = addStatementsAfterPrologue;
+ function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
+ if (statement === undefined)
+ return to;
+ var statementIndex = 0;
+ for (; statementIndex < to.length; ++statementIndex) {
+ if (!isPrologueDirective(to[statementIndex])) {
+ break;
+ }
+ }
+ to.splice(statementIndex, 0, statement);
+ return to;
+ }
+ function isAnyPrologueDirective(node) {
+ return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576);
+ }
+ function insertStatementsAfterStandardPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isPrologueDirective);
+ }
+ ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
+ function insertStatementsAfterCustomPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
+ }
+ ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
+ function insertStatementAfterStandardPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isPrologueDirective);
+ }
+ ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
+ function insertStatementAfterCustomPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
+ }
+ ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
if (text.charCodeAt(commentPos + 1) === 47 &&
commentPos + 2 < commentEnd &&
@@ -6323,7 +6471,7 @@
if (includeJsDoc && ts.hasJSDocNodes(node)) {
return getTokenPosOfNode(node.jsDoc[0]);
}
- if (node.kind === 306 && node._children.length > 0) {
+ if (node.kind === 311 && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -6342,7 +6490,7 @@
}
ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
function isJSDocTypeExpressionOrChild(node) {
- return node.kind === 283 || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
+ return node.kind === 288 || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
}
function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
@@ -6445,7 +6593,7 @@
return node && node.kind === 244 && (!node.body);
}
function isBlockScopedContainerTopLevel(node) {
- return node.kind === 279 ||
+ return node.kind === 284 ||
node.kind === 244 ||
ts.isFunctionLike(node);
}
@@ -6460,7 +6608,7 @@
ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
function isModuleAugmentationExternal(node) {
switch (node.parent.kind) {
- case 279:
+ case 284:
return ts.isExternalModule(node.parent);
case 245:
return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
@@ -6478,7 +6626,7 @@
ts.isEffectiveExternalModule = isEffectiveExternalModule;
function isBlockScope(node, parentNode) {
switch (node.kind) {
- case 279:
+ case 284:
case 246:
case 274:
case 244:
@@ -6501,9 +6649,9 @@
ts.isBlockScope = isBlockScope;
function isDeclarationWithTypeParameters(node) {
switch (node.kind) {
- case 297:
- case 304:
- case 293:
+ case 302:
+ case 309:
+ case 298:
return true;
default:
ts.assertType(node);
@@ -6519,12 +6667,12 @@
case 162:
case 165:
case 166:
- case 289:
+ case 294:
case 240:
case 209:
case 241:
case 242:
- case 303:
+ case 308:
case 239:
case 156:
case 157:
@@ -6662,7 +6810,7 @@
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
- case 279:
+ case 284:
var pos_1 = ts.skipTrivia(sourceFile.text, 0, false);
if (pos_1 === sourceFile.text.length) {
return ts.createTextSpan(0, 0);
@@ -6819,7 +6967,7 @@
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case 150:
return node === parent.constraint;
- case 303:
+ case 308:
return node === parent.constraint;
case 154:
case 153:
@@ -7063,7 +7211,7 @@
}
ts.getContainingClass = getContainingClass;
function getThisContainer(node, includeArrowFunctions) {
- ts.Debug.assert(node.kind !== 279);
+ ts.Debug.assert(node.kind !== 284);
while (true) {
node = node.parent;
if (!node) {
@@ -7102,7 +7250,7 @@
case 161:
case 162:
case 243:
- case 279:
+ case 284:
return node;
}
}
@@ -7171,6 +7319,11 @@
}
}
ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
+ function isSuperOrSuperProperty(node) {
+ return node.kind === 98
+ || isSuperProperty(node);
+ }
+ ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
function isSuperProperty(node) {
var kind = node.kind;
return (kind === 189 || kind === 190)
@@ -7744,7 +7897,7 @@
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
function isJSDocTypeAlias(node) {
- return node.kind === 304 || node.kind === 297;
+ return node.kind === 309 || node.kind === 302;
}
ts.isJSDocTypeAlias = isJSDocTypeAlias;
function isTypeAlias(node) {
@@ -7880,7 +8033,7 @@
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 === 290;
+ return node.dotDotDotToken !== undefined || !!type && type.kind === 295;
}
ts.isRestParameter = isRestParameter;
function getAssignmentTargetKind(node) {
@@ -8086,13 +8239,14 @@
}
ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
function getEffectiveBaseTypeNode(node) {
- if (isInJSFile(node)) {
+ var baseType = getClassExtendsHeritageElement(node);
+ if (baseType && isInJSFile(node)) {
var tag = ts.getJSDocAugmentsTag(node);
if (tag) {
return tag.class;
}
}
- return getClassExtendsHeritageElement(node);
+ return baseType;
}
ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
function getClassExtendsHeritageElement(node) {
@@ -8306,7 +8460,7 @@
|| kind === 158
|| kind === 159
|| kind === 244
- || kind === 279;
+ || kind === 284;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(range) {
@@ -8378,7 +8532,7 @@
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 309:
+ case 314:
return 0;
case 208:
return 1;
@@ -8679,6 +8833,9 @@
lineStart = true;
}
}
+ function getTextPosWithWriteLine() {
+ return lineStart ? output.length : (output.length + newLine.length);
+ }
reset();
return {
write: write,
@@ -8707,7 +8864,8 @@
writeStringLiteral: write,
writeSymbol: function (s, _) { return write(s); },
writeTrailingSemicolon: write,
- writeComment: write
+ writeComment: write,
+ getTextPosWithWriteLine: getTextPosWithWriteLine
};
}
ts.createTextWriter = createTextWriter;
@@ -8824,21 +8982,25 @@
function getSourceFilesToEmit(host, targetSourceFile) {
var options = host.getCompilerOptions();
var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); };
+ var getResolvedProjectReferenceToRedirect = function (fileName) { return host.getResolvedProjectReferenceToRedirect(fileName); };
if (options.outFile || options.out) {
var moduleKind = ts.getEmitModuleKind(options);
var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
return ts.filter(host.getSourceFiles(), function (sourceFile) {
- return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary);
+ return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect);
});
}
else {
var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
- return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); });
+ return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
}
}
ts.getSourceFilesToEmit = getSourceFilesToEmit;
- function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) {
- return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile);
+ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect) {
+ return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
+ !sourceFile.isDeclarationFile &&
+ !isSourceFileFromExternalLibrary(sourceFile) &&
+ !(isJsonSourceFile(sourceFile) && getResolvedProjectReferenceToRedirect(sourceFile.fileName));
}
ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
function getSourceFilePathInNewDir(fileName, host, newDirPath) {
@@ -8972,7 +9134,7 @@
}
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
function isNonTypeAliasTemplate(tag) {
- return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 && tag.parent.tags.some(isJSDocTypeAlias));
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 296 && tag.parent.tags.some(isJSDocTypeAlias));
}
function getEffectiveSetAccessorTypeAnnotationNode(node) {
var parameter = getSetAccessorValueParameter(node);
@@ -9737,7 +9899,7 @@
}
ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
function getObjectFlags(type) {
- return type.flags & 524288 ? type.objectFlags : 0;
+ return type.flags & 3899392 ? type.objectFlags : 0;
}
ts.getObjectFlags = getObjectFlags;
function typeHasCallOrConstructSignatures(type, checker) {
@@ -9803,25 +9965,37 @@
|| kind === 96
|| kind === 132
|| kind === 211
- || kind === 284
- || kind === 285
- || kind === 286
- || kind === 287
- || kind === 288
|| kind === 289
- || kind === 290;
+ || kind === 290
+ || kind === 291
+ || kind === 292
+ || kind === 293
+ || kind === 294
+ || kind === 295;
}
ts.isTypeNodeKind = isTypeNodeKind;
function isAccessExpression(node) {
return node.kind === 189 || node.kind === 190;
}
ts.isAccessExpression = isAccessExpression;
+ function isBundleFileTextLike(section) {
+ switch (section.kind) {
+ case "text":
+ case "internal":
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isBundleFileTextLike = isBundleFileTextLike;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
switch (options.target) {
- case 6:
+ case 7:
return "lib.esnext.full.d.ts";
+ case 6:
+ return "lib.es2019.full.d.ts";
case 5:
return "lib.es2018.full.d.ts";
case 4:
@@ -10147,8 +10321,8 @@
switch (declaration.kind) {
case 72:
return declaration;
- case 305:
- case 299: {
+ case 310:
+ case 304: {
var name = declaration.name;
if (name.kind === 148) {
return name.right;
@@ -10172,7 +10346,7 @@
return undefined;
}
}
- case 304:
+ case 309:
return getNameOfJSDocTypedef(declaration);
case 254: {
var expression = declaration.expression;
@@ -10314,7 +10488,7 @@
return ts.emptyArray;
}
if (ts.isJSDocTypeAlias(node)) {
- ts.Debug.assert(node.parent.kind === 291);
+ ts.Debug.assert(node.parent.kind === 296);
return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
}
if (node.typeParameters) {
@@ -10566,12 +10740,17 @@
return node.kind === 194;
}
ts.isTypeAssertion = isTypeAssertion;
+ function isConstTypeReference(node) {
+ return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
+ node.typeName.escapedText === "const" && !node.typeArguments;
+ }
+ ts.isConstTypeReference = isConstTypeReference;
function isParenthesizedExpression(node) {
return node.kind === 195;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 308) {
+ while (node.kind === 313) {
node = node.expression;
}
return node;
@@ -10910,113 +11089,133 @@
}
ts.isEnumMember = isEnumMember;
function isSourceFile(node) {
- return node.kind === 279;
+ return node.kind === 284;
}
ts.isSourceFile = isSourceFile;
function isBundle(node) {
- return node.kind === 280;
+ return node.kind === 285;
}
ts.isBundle = isBundle;
function isUnparsedSource(node) {
- return node.kind === 281;
+ return node.kind === 286;
}
ts.isUnparsedSource = isUnparsedSource;
+ function isUnparsedPrepend(node) {
+ return node.kind === 280;
+ }
+ ts.isUnparsedPrepend = isUnparsedPrepend;
+ function isUnparsedTextLike(node) {
+ switch (node.kind) {
+ case 281:
+ case 282:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isUnparsedTextLike = isUnparsedTextLike;
+ function isUnparsedNode(node) {
+ return isUnparsedTextLike(node) ||
+ node.kind === 279 ||
+ node.kind === 283;
+ }
+ ts.isUnparsedNode = isUnparsedNode;
function isJSDocTypeExpression(node) {
- return node.kind === 283;
+ return node.kind === 288;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 284;
+ return node.kind === 289;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 285;
+ return node.kind === 290;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 286;
+ return node.kind === 291;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 287;
+ return node.kind === 292;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 288;
+ return node.kind === 293;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 289;
+ return node.kind === 294;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 290;
+ return node.kind === 295;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 291;
+ return node.kind === 296;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 295;
+ return node.kind === 300;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 296;
+ return node.kind === 301;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocEnumTag(node) {
- return node.kind === 298;
+ return node.kind === 303;
}
ts.isJSDocEnumTag = isJSDocEnumTag;
function isJSDocThisTag(node) {
- return node.kind === 301;
+ return node.kind === 306;
}
ts.isJSDocThisTag = isJSDocThisTag;
function isJSDocParameterTag(node) {
- return node.kind === 299;
+ return node.kind === 304;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 300;
+ return node.kind === 305;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 302;
+ return node.kind === 307;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 303;
+ return node.kind === 308;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 304;
+ return node.kind === 309;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 305;
+ return node.kind === 310;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 305 || node.kind === 299;
+ return node.kind === 310 || node.kind === 304;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 292;
+ return node.kind === 297;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
function isJSDocCallbackTag(node) {
- return node.kind === 297;
+ return node.kind === 302;
}
ts.isJSDocCallbackTag = isJSDocCallbackTag;
function isJSDocSignature(node) {
- return node.kind === 293;
+ return node.kind === 298;
}
ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
(function (ts) {
function isSyntaxList(n) {
- return n.kind === 306;
+ return n.kind === 311;
}
ts.isSyntaxList = isSyntaxList;
function isNode(node) {
@@ -11146,11 +11345,11 @@
switch (kind) {
case 155:
case 160:
- case 293:
+ case 298:
case 161:
case 162:
case 165:
- case 289:
+ case 294:
case 166:
return true;
default:
@@ -11401,8 +11600,8 @@
case 208:
case 212:
case 210:
- case 309:
- case 308:
+ case 314:
+ case 313:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -11415,11 +11614,11 @@
}
ts.isAssertionExpression = isAssertionExpression;
function isPartiallyEmittedExpression(node) {
- return node.kind === 308;
+ return node.kind === 313;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
function isNotEmittedStatement(node) {
- return node.kind === 307;
+ return node.kind === 312;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
function isNotEmittedOrPartiallyEmittedNode(node) {
@@ -11519,9 +11718,9 @@
|| kind === 242
|| kind === 150
|| kind === 237
- || kind === 304
- || kind === 297
- || kind === 305;
+ || kind === 309
+ || kind === 302
+ || kind === 310;
}
function isDeclarationStatementKind(kind) {
return kind === 239
@@ -11556,13 +11755,13 @@
|| kind === 219
|| kind === 224
|| kind === 231
- || kind === 307
- || kind === 311
- || kind === 310;
+ || kind === 312
+ || kind === 316
+ || kind === 315;
}
function isDeclaration(node) {
if (node.kind === 150) {
- return node.parent.kind !== 303 || ts.isInJSFile(node);
+ return (node.parent && node.parent.kind !== 308) || ts.isInJSFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -11640,15 +11839,15 @@
}
ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
function isJSDocNode(node) {
- return node.kind >= 283 && node.kind <= 305;
+ return node.kind >= 288 && node.kind <= 310;
}
ts.isJSDocNode = isJSDocNode;
function isJSDocCommentContainingNode(node) {
- return node.kind === 291 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
+ return node.kind === 296 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
}
ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
function isJSDocTag(node) {
- return node.kind >= 294 && node.kind <= 305;
+ return node.kind >= 299 && node.kind <= 310;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -11950,6 +12149,10 @@
return !!(compilerOptions.declaration || compilerOptions.composite);
}
ts.getEmitDeclarations = getEmitDeclarations;
+ function isIncrementalCompilation(options) {
+ return !!(options.incremental || options.composite);
+ }
+ ts.isIncrementalCompilation = isIncrementalCompilation;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
}
@@ -12492,7 +12695,7 @@
return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
}
ts.getRegexFromPattern = getRegexFromPattern;
- function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) {
+ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
path = ts.normalizePath(path);
currentDirectory = ts.normalizePath(currentDirectory);
var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
@@ -12500,12 +12703,18 @@
var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
+ var visited = ts.createMap();
+ var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
var basePath = _a[_i];
visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
}
return ts.flatten(results);
function visitDirectory(path, absolutePath, depth) {
+ var canonicalPath = toCanonical(realpath(absolutePath));
+ if (visited.has(canonicalPath))
+ return;
+ visited.set(canonicalPath, true);
var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
var _loop_1 = function (current) {
var name = combinePaths(path, current);
@@ -12830,6 +13039,19 @@
return arr.slice(index);
}
ts.sliceAfter = sliceAfter;
+ function addRelatedInfo(diagnostic) {
+ var _a;
+ var relatedInformation = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ relatedInformation[_i - 1] = arguments[_i];
+ }
+ if (!diagnostic.relatedInformation) {
+ diagnostic.relatedInformation = [];
+ }
+ (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
+ return diagnostic;
+ }
+ ts.addRelatedInfo = addRelatedInfo;
function minAndMax(arr, getValue) {
Debug.assert(arr.length !== 0);
var min = getValue(arr[0]);
@@ -13003,7 +13225,7 @@
var IdentifierConstructor;
var SourceFileConstructor;
function createNode(kind, pos, end) {
- if (kind === 279) {
+ if (kind === 284) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 72) {
@@ -13240,7 +13462,7 @@
case 218:
case 245:
return visitNodes(cbNode, cbNodes, node.statements);
- case 279:
+ case 284:
return visitNodes(cbNode, cbNodes, node.statements) ||
visitNode(cbNode, node.endOfFileToken);
case 219:
@@ -13389,7 +13611,7 @@
return visitNode(cbNode, node.expression);
case 258:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 309:
+ case 314:
return visitNodes(cbNode, cbNodes, node.elements);
case 260:
return visitNode(cbNode, node.openingElement) ||
@@ -13418,60 +13640,60 @@
return visitNode(cbNode, node.tagName);
case 171:
case 172:
- case 283:
- case 287:
- case 286:
case 288:
- case 290:
+ case 292:
+ case 291:
+ case 293:
+ case 295:
return visitNode(cbNode, node.type);
- case 289:
+ case 294:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 291:
+ case 296:
return visitNodes(cbNode, cbNodes, node.tags);
- case 299:
- case 305:
+ case 304:
+ case 310:
return visitNode(cbNode, node.tagName) ||
(node.isNameFirst
? visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression)
: visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name));
- case 295:
+ case 300:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.class);
- case 303:
+ case 308:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.constraint) ||
visitNodes(cbNode, cbNodes, node.typeParameters);
- case 304:
+ case 309:
return visitNode(cbNode, node.tagName) ||
(node.typeExpression &&
- node.typeExpression.kind === 283
+ node.typeExpression.kind === 288
? visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName)
: visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression));
- case 297:
+ case 302:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
- case 300:
- case 302:
- case 301:
- case 298:
+ case 305:
+ case 307:
+ case 306:
+ case 303:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.typeExpression);
- case 293:
+ case 298:
return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
- case 292:
+ case 297:
return ts.forEach(node.jsDocPropertyTags, cbNode);
- case 294:
- case 296:
+ case 299:
+ case 301:
return visitNode(cbNode, node.tagName);
- case 308:
+ case 313:
return visitNode(cbNode, node.expression);
}
}
@@ -13524,7 +13746,7 @@
ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
var Parser;
(function (Parser) {
- var scanner = ts.createScanner(6, true);
+ var scanner = ts.createScanner(7, true);
var disallowInAndDecoratorContext = 2048 | 8192;
var NodeConstructor;
var TokenConstructor;
@@ -13722,7 +13944,7 @@
}
Parser.fixupParentReferences = fixupParentReferences;
function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
- var sourceFile = new SourceFileConstructor(279, 0, sourceText.length);
+ var sourceFile = new SourceFileConstructor(284, 0, sourceText.length);
nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
@@ -14669,9 +14891,9 @@
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(284);
+ var result = createNode(289);
if (postFixEquals) {
- return createPostfixType(288, result);
+ return createPostfixType(293, result);
}
else {
nextToken();
@@ -14679,7 +14901,7 @@
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(287);
+ var result = createNode(292);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -14693,18 +14915,18 @@
token() === 30 ||
token() === 59 ||
token() === 50) {
- var result = createNode(285, pos);
+ var result = createNode(290, pos);
return finishNode(result);
}
else {
- var result = createNode(286, pos);
+ var result = createNode(291, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(289);
+ var result = createNodeWithJSDoc(294);
nextToken();
fillSignature(57, 4 | 32, result);
return finishNode(result);
@@ -14728,12 +14950,12 @@
var type = parseTypeOrTypePredicate();
scanner.setInJSDocType(false);
if (dotdotdot) {
- var variadic = createNode(290, dotdotdot.pos);
+ var variadic = createNode(295, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 59) {
- return createPostfixType(288, type);
+ return createPostfixType(293, type);
}
return type;
}
@@ -15027,7 +15249,7 @@
return finishNode(node);
}
var type = parseType();
- if (!(contextFlags & 2097152) && type.kind === 286 && type.pos === type.type.pos) {
+ if (!(contextFlags & 2097152) && type.kind === 291 && type.pos === type.type.pos) {
type.kind = 171;
}
return type;
@@ -15164,6 +15386,7 @@
case 135:
case 146:
case 123:
+ case 133:
case 139:
case 142:
case 106:
@@ -15210,13 +15433,13 @@
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 52:
- type = createPostfixType(287, type);
+ type = createPostfixType(292, type);
break;
case 56:
if (!(contextFlags & 2097152) && lookAhead(nextTokenIsStartOfType)) {
return type;
}
- type = createPostfixType(286, type);
+ type = createPostfixType(291, type);
break;
case 22:
parseExpected(22);
@@ -15266,6 +15489,7 @@
switch (operator) {
case 129:
case 142:
+ case 133:
return parseTypeOperator(operator);
case 127:
return parseInferType();
@@ -15954,7 +16178,8 @@
}
function parseJsxText() {
var node = createNode(11);
- node.containsOnlyWhiteSpaces = currentToken === 12;
+ node.text = scanner.getTokenValue();
+ node.containsOnlyTriviaWhiteSpaces = currentToken === 12;
currentToken = scanner.scanJsxToken();
return finishNode(node);
}
@@ -17532,8 +17757,8 @@
var JSDocParser;
(function (JSDocParser) {
function parseJSDocTypeExpressionForTests(content, start, length) {
- initializeState(content, 6, undefined, 1);
- sourceFile = createSourceFile("file.js", 6, 1, false);
+ initializeState(content, 7, undefined, 1);
+ sourceFile = createSourceFile("file.js", 7, 1, false);
scanner.setText(content, start, length);
currentToken = scanner.scan();
var jsDocTypeExpression = parseJSDocTypeExpression();
@@ -17543,7 +17768,7 @@
}
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(283);
+ var result = createNode(288);
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18);
result.type = doInsideOfContext(2097152, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -17554,7 +17779,7 @@
}
JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
function parseIsolatedJSDocComment(content, start, length) {
- initializeState(content, 6, undefined, 1);
+ initializeState(content, 7, undefined, 1);
sourceFile = { languageVariant: 0, text: content };
var jsDoc = parseJSDocCommentWorker(start, length);
var diagnostics = parseDiagnostics;
@@ -17680,7 +17905,7 @@
}
}
function createJSDocComment() {
- var result = createNode(291, start);
+ var result = createNode(296, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -17839,7 +18064,7 @@
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(start, tagName) {
- var result = createNode(294, start);
+ var result = createNode(299, start);
result.tagName = tagName;
return finishNode(result);
}
@@ -17895,8 +18120,8 @@
typeExpression = tryParseTypeExpression();
}
var result = target === 1 ?
- createNode(305, start) :
- createNode(299, start);
+ createNode(310, start) :
+ createNode(304, start);
var comment = parseTagComments(indent + scanner.getStartPos() - start);
var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target, indent);
if (nestedTypeLiteral) {
@@ -17913,18 +18138,18 @@
}
function parseNestedTypeLiteral(typeExpression, name, target, indent) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(283, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(288, 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, indent, name); })) {
- if (child.kind === 299 || child.kind === 305) {
+ if (child.kind === 304 || child.kind === 310) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(292, start_2);
+ jsdocTypeLiteral = createNode(297, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 169) {
jsdocTypeLiteral.isArrayType = true;
@@ -17935,25 +18160,25 @@
}
}
function parseReturnTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 300; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 305; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(300, start);
+ var result = createNode(305, start);
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 302; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 307; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(302, start);
+ var result = createNode(307, start);
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(true);
return finishNode(result);
}
function parseAugmentsTag(start, tagName) {
- var result = createNode(295, start);
+ var result = createNode(300, start);
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
return finishNode(result);
@@ -17980,19 +18205,19 @@
return node;
}
function parseClassTag(start, tagName) {
- var tag = createNode(296, start);
+ var tag = createNode(301, start);
tag.tagName = tagName;
return finishNode(tag);
}
function parseThisTag(start, tagName) {
- var tag = createNode(301, start);
+ var tag = createNode(306, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(true);
skipWhitespace();
return finishNode(tag);
}
function parseEnumTag(start, tagName) {
- var tag = createNode(298, start);
+ var tag = createNode(303, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(true);
skipWhitespace();
@@ -18001,7 +18226,7 @@
function parseTypedefTag(start, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespaceOrAsterisk();
- var typedefTag = createNode(304, start);
+ var typedefTag = createNode(309, start);
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace();
typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
@@ -18015,9 +18240,9 @@
var childTypeTag = void 0;
while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(292, start);
+ jsdocTypeLiteral = createNode(297, start);
}
- if (child.kind === 302) {
+ if (child.kind === 307) {
if (childTypeTag) {
break;
}
@@ -18062,14 +18287,14 @@
return typeNameOrNamespaceName;
}
function parseCallbackTag(start, tagName, indent) {
- var callbackTag = createNode(297, start);
+ var callbackTag = createNode(302, start);
callbackTag.tagName = tagName;
callbackTag.fullName = parseJSDocTypeNameWithNamespace();
callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
skipWhitespace();
callbackTag.comment = parseTagComments(indent);
var child;
- var jsdocSignature = createNode(293, start);
+ var jsdocSignature = createNode(298, start);
jsdocSignature.parameters = [];
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4, indent); })) {
jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
@@ -18077,7 +18302,7 @@
var returnTag = tryParse(function () {
if (parseOptionalJsdoc(58)) {
var tag = parseTag(indent);
- if (tag && tag.kind === 300) {
+ if (tag && tag.kind === 305) {
return tag;
}
}
@@ -18122,7 +18347,7 @@
case 58:
if (canParseTag) {
var child = tryParseChildTag(target, indent);
- if (child && (child.kind === 299 || child.kind === 305) &&
+ if (child && (child.kind === 304 || child.kind === 310) &&
target !== 4 &&
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
@@ -18191,7 +18416,7 @@
skipWhitespace();
typeParameters.push(typeParameter);
} while (parseOptionalJsdoc(27));
- var result = createNode(303, start);
+ var result = createNode(308, start);
result.tagName = tagName;
result.constraint = constraint;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -18755,6 +18980,7 @@
["es2016", "lib.es2016.d.ts"],
["es2017", "lib.es2017.d.ts"],
["es2018", "lib.es2018.d.ts"],
+ ["es2019", "lib.es2019.d.ts"],
["esnext", "lib.esnext.d.ts"],
["dom", "lib.dom.d.ts"],
["dom.iterable", "lib.dom.iterable.d.ts"],
@@ -18776,12 +19002,16 @@
["es2017.string", "lib.es2017.string.d.ts"],
["es2017.intl", "lib.es2017.intl.d.ts"],
["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
+ ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
["es2018.intl", "lib.es2018.intl.d.ts"],
["es2018.promise", "lib.es2018.promise.d.ts"],
["es2018.regexp", "lib.es2018.regexp.d.ts"],
- ["esnext.array", "lib.esnext.array.d.ts"],
- ["esnext.symbol", "lib.esnext.symbol.d.ts"],
- ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"],
+ ["es2019.array", "lib.es2019.array.d.ts"],
+ ["es2019.string", "lib.es2019.string.d.ts"],
+ ["es2019.symbol", "lib.es2019.symbol.d.ts"],
+ ["esnext.array", "lib.es2019.array.d.ts"],
+ ["esnext.symbol", "lib.es2019.symbol.d.ts"],
+ ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
["esnext.intl", "lib.esnext.intl.d.ts"],
["esnext.bigint", "lib.esnext.bigint.d.ts"]
];
@@ -18913,14 +19143,15 @@
es2016: 3,
es2017: 4,
es2018: 5,
- esnext: 6,
+ es2019: 6,
+ esnext: 7,
}),
affectsSourceFile: true,
affectsModuleResolution: true,
paramType: ts.Diagnostics.VERSION,
showInSimplifiedHelpView: true,
category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT,
+ description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT,
},
{
name: "module",
@@ -19042,6 +19273,22 @@
description: ts.Diagnostics.Enable_project_compilation,
},
{
+ name: "incremental",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_incremental_compilation,
+ },
+ {
+ name: "tsBuildInfoFile",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE,
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
+ },
+ {
name: "removeComments",
type: "boolean",
showInSimplifiedHelpView: true,
@@ -22224,7 +22471,7 @@
return "__constructor";
case 165:
case 160:
- case 293:
+ case 298:
return "__call";
case 166:
case 161:
@@ -22233,7 +22480,7 @@
return "__index";
case 255:
return "__export";
- case 279:
+ case 284:
return "export=";
case 204:
if (ts.getAssignmentDeclarationKind(node) === 2) {
@@ -22241,10 +22488,10 @@
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 289:
+ case 294:
return (ts.isJSDocConstructSignature(node) ? "__new" : "__call");
case 151:
- ts.Debug.assert(node.parent.kind === 289, "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 === 294, "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;
@@ -22290,24 +22537,34 @@
message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
messageNeedsName_1 = false;
}
- if (symbol.declarations && symbol.declarations.length) {
+ var multipleDefaultExports_1 = false;
+ if (ts.length(symbol.declarations)) {
if (isDefaultExport) {
message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
messageNeedsName_1 = false;
+ multipleDefaultExports_1 = true;
}
else {
if (symbol.declarations && symbol.declarations.length &&
(node.kind === 254 && !node.isExportEquals)) {
message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
messageNeedsName_1 = false;
+ multipleDefaultExports_1 = true;
}
}
}
- 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);
+ var declarationName_1 = ts.getNameOfDeclaration(node) || node;
+ var relatedInformation_1 = [];
+ ts.forEach(symbol.declarations, function (declaration, index) {
+ var decl = ts.getNameOfDeclaration(declaration) || declaration;
+ var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
+ file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo(diag, createDiagnosticForNode(declarationName_1, index === 0 ? ts.Diagnostics.Another_export_default_is_here : ts.Diagnostics.and_here)) : diag);
+ if (multipleDefaultExports_1) {
+ relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
+ }
+ });
+ var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
+ file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInformation_1)) : diag);
symbol = createSymbol(0, name);
}
}
@@ -22396,7 +22653,7 @@
if (hasExplicitReturn)
node.flags |= 256;
}
- if (node.kind === 279) {
+ if (node.kind === 284) {
node.flags |= emitFlags;
}
if (currentReturnTarget) {
@@ -22540,11 +22797,11 @@
case 191:
bindCallExpressionFlow(node);
break;
- case 304:
- case 297:
+ case 309:
+ case 302:
bindJSDocTypeAlias(node);
break;
- case 279: {
+ case 284: {
bindEachFunctionsFirst(node.statements);
bind(node.endOfFileToken);
break;
@@ -23184,7 +23441,7 @@
case 243:
case 188:
case 168:
- case 292:
+ case 297:
case 268:
return 1;
case 241:
@@ -23193,7 +23450,7 @@
case 242:
case 181:
return 1 | 32;
- case 279:
+ case 284:
return 1 | 4 | 32;
case 156:
if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
@@ -23205,8 +23462,8 @@
case 158:
case 159:
case 160:
- case 293:
- case 289:
+ case 298:
+ case 294:
case 165:
case 161:
case 162:
@@ -23240,7 +23497,7 @@
switch (container.kind) {
case 244:
return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 279:
+ case 284:
return declareSourceFileMember(node, symbolFlags, symbolExcludes);
case 209:
case 240:
@@ -23248,7 +23505,7 @@
case 243:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 168:
- case 292:
+ case 297:
case 188:
case 241:
case 268:
@@ -23257,7 +23514,7 @@
case 166:
case 160:
case 161:
- case 293:
+ case 298:
case 162:
case 156:
case 155:
@@ -23267,9 +23524,9 @@
case 239:
case 196:
case 197:
- case 289:
- case 304:
- case 297:
+ case 294:
+ case 309:
+ case 302:
case 242:
case 181:
return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
@@ -23286,8 +23543,8 @@
: declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node) {
- var body = node.kind === 279 ? node : node.body;
- if (body && (body.kind === 279 || body.kind === 245)) {
+ var body = node.kind === 284 ? node : node.body;
+ if (body && (body.kind === 284 || body.kind === 245)) {
for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
var stat = _a[_i];
if (stat.kind === 255 || stat.kind === 254) {
@@ -23397,7 +23654,7 @@
case 244:
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
- case 279:
+ case 284:
if (ts.isExternalOrCommonJsModule(container)) {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
@@ -23514,7 +23771,7 @@
}
function checkStrictModeFunctionDeclaration(node) {
if (languageVersion < 2) {
- if (blockScopeContainer.kind !== 279 &&
+ if (blockScopeContainer.kind !== 284 &&
blockScopeContainer.kind !== 244 &&
!ts.isFunctionLike(blockScopeContainer)) {
var errorSpan = ts.getErrorSpanForNode(file, node);
@@ -23743,12 +24000,12 @@
case 159:
return bindPropertyOrMethodOrAccessor(node, 65536, 67187647);
case 165:
- case 289:
- case 293:
+ case 294:
+ case 298:
case 166:
return bindFunctionOrConstructorType(node);
case 168:
- case 292:
+ case 297:
case 181:
return bindAnonymousTypeWorker(node);
case 188:
@@ -23803,7 +24060,7 @@
return bindExportDeclaration(node);
case 254:
return bindExportAssignment(node);
- case 279:
+ case 284:
updateStrictModeStatementList(node.statements);
return bindSourceFileIfExternalModule();
case 218:
@@ -23812,21 +24069,21 @@
}
case 245:
return updateStrictModeStatementList(node.statements);
- case 299:
- if (node.parent.kind === 293) {
+ case 304:
+ if (node.parent.kind === 298) {
return bindParameter(node);
}
- if (node.parent.kind !== 292) {
+ if (node.parent.kind !== 297) {
break;
}
- case 305:
+ case 310:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 293 ?
4 | 16777216 :
4;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0);
- case 304:
- case 297:
+ case 309:
+ case 302:
return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
}
}
@@ -23977,7 +24234,13 @@
var symbolTable = ts.hasModifier(thisContainer, 32) ? containingClass.symbol.exports : containingClass.symbol.members;
declareSymbol(symbolTable, containingClass.symbol, node, 4, 0, true);
break;
- case 279:
+ case 284:
+ if (thisContainer.commonJsModuleIndicator) {
+ declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 | 1048576, 0);
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1, 67220414);
+ }
break;
default:
ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer));
@@ -23987,7 +24250,7 @@
if (node.expression.kind === 100) {
bindThisPropertyAssignment(node);
}
- else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279) {
+ else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 284) {
if (ts.isPrototypeAccess(node.expression)) {
bindPrototypePropertyAssignment(node, node.parent);
}
@@ -24016,7 +24279,7 @@
}
function bindObjectDefinePropertyAssignment(node) {
var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
- var isToplevel = node.parent.parent.kind === 279;
+ var isToplevel = node.parent.parent.kind === 284;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, false);
bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, false);
}
@@ -24072,8 +24335,8 @@
function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
var namespaceSymbol = lookupSymbolForPropertyAccess(name);
var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
- ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279
- : propertyAccess.parent.parent.kind === 279;
+ ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 284
+ : propertyAccess.parent.parent.kind === 284;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty);
bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
}
@@ -24180,7 +24443,7 @@
}
}
function bindParameter(node) {
- if (node.kind === 299 && container.kind !== 293) {
+ if (node.kind === 304 && container.kind !== 298) {
return;
}
if (inStrictMode && !(node.flags & 4194304)) {
@@ -24411,53 +24674,50 @@
ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
function computeCallExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
+ var callee = ts.skipOuterExpressions(node.expression);
var expression = node.expression;
if (node.typeArguments) {
- transformFlags |= 3;
+ transformFlags |= 1;
}
- if (subtreeFlags & 131072
- || (expression.transformFlags & (33554432 | 67108864))) {
- transformFlags |= 192;
- if (expression.transformFlags & 67108864) {
- transformFlags |= 8192;
+ if (subtreeFlags & 4096 || ts.isSuperOrSuperProperty(callee)) {
+ transformFlags |= 128;
+ if (ts.isSuperProperty(callee)) {
+ transformFlags |= 2048;
}
}
if (expression.kind === 92) {
- transformFlags |= 16777216;
- if (subtreeFlags & 8192) {
- transformFlags |= 16384;
- }
+ transformFlags |= 524288;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~637666625;
+ return transformFlags & ~536875008;
}
function computeNewExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (node.typeArguments) {
- transformFlags |= 3;
+ transformFlags |= 1;
}
- if (subtreeFlags & 131072) {
- transformFlags |= 192;
+ if (subtreeFlags & 4096) {
+ transformFlags |= 128;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~637666625;
+ return transformFlags & ~536875008;
}
function computeBinaryExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
var operatorTokenKind = node.operatorToken.kind;
var leftKind = node.left.kind;
if (operatorTokenKind === 59 && leftKind === 188) {
- transformFlags |= 8 | 192 | 3072;
+ transformFlags |= 16 | 128 | 512;
}
else if (operatorTokenKind === 59 && leftKind === 187) {
- transformFlags |= 192 | 3072;
+ transformFlags |= 128 | 512;
}
else if (operatorTokenKind === 41
|| operatorTokenKind === 63) {
- transformFlags |= 32;
+ transformFlags |= 64;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~637535553;
+ return transformFlags & ~536870912;
}
function computeParameter(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -24466,82 +24726,72 @@
var dotDotDotToken = node.dotDotDotToken;
if (node.questionToken
|| node.type
- || (subtreeFlags & 4096 && ts.some(node.decorators))
+ || (subtreeFlags & 1024 && ts.some(node.decorators))
|| ts.isThisIdentifier(name)) {
- transformFlags |= 3;
+ transformFlags |= 1;
}
if (ts.hasModifier(node, 92)) {
- transformFlags |= 3 | 4096;
+ transformFlags |= 1 | 1024;
}
- if (subtreeFlags & 262144) {
- transformFlags |= 8;
+ if (subtreeFlags & 8192) {
+ transformFlags |= 16;
}
- if (subtreeFlags & 2097152 || initializer || dotDotDotToken) {
- transformFlags |= 192 | 65536;
+ if (subtreeFlags & 65536 || initializer || dotDotDotToken) {
+ transformFlags |= 128;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~637535553;
+ return transformFlags & ~536870912;
}
function computeParenthesizedExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
var expression = node.expression;
var expressionKind = expression.kind;
- var expressionTransformFlags = expression.transformFlags;
if (expressionKind === 212
|| expressionKind === 194) {
- transformFlags |= 3;
- }
- if (expressionTransformFlags & 1024) {
- transformFlags |= 1024;
+ transformFlags |= 1;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~536872257;
+ return transformFlags & ~536870912;
}
function computeClassDeclaration(node, subtreeFlags) {
var transformFlags;
if (ts.hasModifier(node, 2)) {
- transformFlags = 3;
+ transformFlags = 1;
}
else {
- transformFlags = subtreeFlags | 192;
- if ((subtreeFlags & 4096)
+ transformFlags = subtreeFlags | 128;
+ if ((subtreeFlags & 1024)
|| node.typeParameters) {
- transformFlags |= 3;
- }
- if (subtreeFlags & 32768) {
- transformFlags |= 8192;
+ transformFlags |= 1;
}
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~638121281;
+ return transformFlags & ~536888320;
}
function computeClassExpression(node, subtreeFlags) {
- var transformFlags = subtreeFlags | 192;
- if (subtreeFlags & 4096
+ var transformFlags = subtreeFlags | 128;
+ if (subtreeFlags & 1024
|| node.typeParameters) {
- transformFlags |= 3;
- }
- if (subtreeFlags & 32768) {
- transformFlags |= 8192;
+ transformFlags |= 1;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~638121281;
+ return transformFlags & ~536888320;
}
function computeHeritageClause(node, subtreeFlags) {
var transformFlags = subtreeFlags;
switch (node.token) {
case 86:
- transformFlags |= 192;
+ transformFlags |= 128;
break;
case 109:
- transformFlags |= 3;
+ transformFlags |= 1;
break;
default:
ts.Debug.fail("Unexpected token for heritage clause");
break;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~637535553;
+ return transformFlags & ~536870912;
}
function computeCatchClause(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -24549,52 +24799,52 @@
transformFlags |= 8;
}
else if (ts.isBindingPattern(node.variableDeclaration.name)) {
- transformFlags |= 192;
+ transformFlags |= 128;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~637797697;
+ return transformFlags & ~536879104;
}
function computeExpressionWithTypeArguments(node, subtreeFlags) {
- var transformFlags = subtreeFlags | 192;
+ var transformFlags = subtreeFlags | 128;
if (node.typeArguments) {
- transformFlags |= 3;
+ transformFlags |= 1;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~637535553;
+ return transformFlags & ~536870912;
}
function computeConstructor(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (ts.hasModifier(node, 2270)
|| !node.body) {
- transformFlags |= 3;
+ transformFlags |= 1;
}
- if (subtreeFlags & 262144) {
- transformFlags |= 8;
+ if (subtreeFlags & 8192) {
+ transformFlags |= 16;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~653616449;
+ return transformFlags & ~537372672;
}
function computeMethod(node, subtreeFlags) {
- var transformFlags = subtreeFlags | 192;
+ var transformFlags = subtreeFlags | 128;
if (node.decorators
|| ts.hasModifier(node, 2270)
|| node.typeParameters
|| node.type
|| (node.name && ts.isComputedPropertyName(node.name))
|| !node.body) {
- transformFlags |= 3;
+ transformFlags |= 1;
}
- if (subtreeFlags & 262144) {
- transformFlags |= 8;
+ if (subtreeFlags & 8192) {
+ transformFlags |= 16;
}
if (ts.hasModifier(node, 256)) {
- transformFlags |= node.asteriskToken ? 8 : 16;
+ transformFlags |= node.asteriskToken ? 16 : 32;
}
if (node.asteriskToken) {
- transformFlags |= 768;
+ transformFlags |= 256;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~653616449;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~537372672);
}
function computeAccessor(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -24603,198 +24853,182 @@
|| node.type
|| (node.name && ts.isComputedPropertyName(node.name))
|| !node.body) {
- transformFlags |= 3;
+ transformFlags |= 1;
}
- if (subtreeFlags & 262144) {
- transformFlags |= 8;
+ if (subtreeFlags & 8192) {
+ transformFlags |= 16;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~653616449;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~537372672);
}
function computePropertyDeclaration(node, subtreeFlags) {
- var transformFlags = subtreeFlags | 3;
+ var transformFlags = subtreeFlags | 1;
if (node.initializer || ts.isComputedPropertyName(node.name)) {
- transformFlags |= 4096;
+ transformFlags |= 1024;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~637535553;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~536872960);
}
function computeFunctionDeclaration(node, subtreeFlags) {
var transformFlags;
var modifierFlags = ts.getModifierFlags(node);
var body = node.body;
if (!body || (modifierFlags & 2)) {
- transformFlags = 3;
+ transformFlags = 1;
}
else {
- transformFlags = subtreeFlags | 8388608;
+ transformFlags = subtreeFlags | 262144;
if (modifierFlags & 2270
|| node.typeParameters
|| node.type) {
- transformFlags |= 3;
+ transformFlags |= 1;
}
if (modifierFlags & 256) {
- transformFlags |= node.asteriskToken ? 8 : 16;
- }
- if (subtreeFlags & 262144) {
- transformFlags |= 8;
+ transformFlags |= node.asteriskToken ? 16 : 32;
}
- if (subtreeFlags & 81920) {
- transformFlags |= 192;
+ if (subtreeFlags & 8192) {
+ transformFlags |= 16;
}
if (node.asteriskToken) {
- transformFlags |= 768;
+ transformFlags |= 256;
}
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~653620545;
+ return transformFlags & ~537373696;
}
function computeFunctionExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (ts.hasModifier(node, 2270)
|| node.typeParameters
|| node.type) {
- transformFlags |= 3;
+ transformFlags |= 1;
}
if (ts.hasModifier(node, 256)) {
- transformFlags |= node.asteriskToken ? 8 : 16;
- }
- if (subtreeFlags & 262144) {
- transformFlags |= 8;
+ transformFlags |= node.asteriskToken ? 16 : 32;
}
- if (subtreeFlags & 81920) {
- transformFlags |= 192;
+ if (subtreeFlags & 8192) {
+ transformFlags |= 16;
}
if (node.asteriskToken) {
- transformFlags |= 768;
+ transformFlags |= 256;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~653620545;
+ return transformFlags & ~537373696;
}
function computeArrowFunction(node, subtreeFlags) {
- var transformFlags = subtreeFlags | 192;
+ var transformFlags = subtreeFlags | 128;
if (ts.hasModifier(node, 2270)
|| node.typeParameters
|| node.type) {
- transformFlags |= 3;
+ transformFlags |= 1;
}
if (ts.hasModifier(node, 256)) {
- transformFlags |= 16;
- }
- if (subtreeFlags & 262144) {
- transformFlags |= 8;
+ transformFlags |= 32;
}
if (subtreeFlags & 8192) {
- transformFlags |= 16384;
+ transformFlags |= 16;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~653604161;
+ return transformFlags & ~537371648;
}
function computePropertyAccess(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- if (transformFlags & 33554432) {
- transformFlags ^= 33554432;
- transformFlags |= 67108864 | 16 | 8;
+ if (node.expression.kind === 98) {
+ transformFlags |= 32 | 16;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~570426689;
+ return transformFlags & ~536870912;
}
function computeElementAccess(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- var expression = node.expression;
- var expressionFlags = expression.transformFlags;
- if (expressionFlags & 33554432) {
- transformFlags &= ~33554432;
- transformFlags |= 67108864 | 16 | 8;
+ if (node.expression.kind === 98) {
+ transformFlags |= 32 | 16;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~570426689;
+ return transformFlags & ~536870912;
}
function computeVariableDeclaration(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- transformFlags |= 192 | 2097152;
- if (subtreeFlags & 262144) {
- transformFlags |= 8;
+ transformFlags |= 128 | 65536;
+ if (subtreeFlags & 8192) {
+ transformFlags |= 16;
}
if (node.type) {
- transformFlags |= 3;
+ transformFlags |= 1;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~637535553;
+ return transformFlags & ~536870912;
}
function computeVariableStatement(node, subtreeFlags) {
var transformFlags;
var declarationListTransformFlags = node.declarationList.transformFlags;
if (ts.hasModifier(node, 2)) {
- transformFlags = 3;
+ transformFlags = 1;
}
else {
transformFlags = subtreeFlags;
- if (declarationListTransformFlags & 2097152) {
- transformFlags |= 192;
+ if (declarationListTransformFlags & 65536) {
+ transformFlags |= 128;
}
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~637535553;
+ return transformFlags & ~536870912;
}
function computeLabeledStatement(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- if (subtreeFlags & 1048576
+ if (subtreeFlags & 32768
&& ts.isIterationStatement(node, true)) {
- transformFlags |= 192;
+ transformFlags |= 128;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~637535553;
+ return transformFlags & ~536870912;
}
function computeImportEquals(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
- transformFlags |= 3;
+ transformFlags |= 1;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~637535553;
+ return transformFlags & ~536870912;
}
function computeExpressionStatement(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- if (node.expression.transformFlags & 1024) {
- transformFlags |= 192;
- }
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~637535553;
+ return transformFlags & ~536870912;
}
function computeModuleDeclaration(node, subtreeFlags) {
- var transformFlags = 3;
+ var transformFlags = 1;
var modifierFlags = ts.getModifierFlags(node);
if ((modifierFlags & 2) === 0) {
transformFlags |= subtreeFlags;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~647001409;
+ return transformFlags & ~537168896;
}
function computeVariableDeclarationList(node, subtreeFlags) {
- var transformFlags = subtreeFlags | 8388608;
- if (subtreeFlags & 2097152) {
- transformFlags |= 192;
+ var transformFlags = subtreeFlags | 262144;
+ if (subtreeFlags & 65536) {
+ transformFlags |= 128;
}
if (node.flags & 3) {
- transformFlags |= 192 | 1048576;
+ transformFlags |= 128 | 32768;
}
node.transformFlags = transformFlags | 536870912;
- return transformFlags & ~639894849;
+ return transformFlags & ~536944640;
}
function computeOther(node, kind, subtreeFlags) {
var transformFlags = subtreeFlags;
- var excludeFlags = 637535553;
+ var excludeFlags = 536870912;
switch (kind) {
case 121:
case 201:
- transformFlags |= 8 | 16;
+ transformFlags |= 16 | 32;
break;
case 194:
case 212:
- case 308:
- transformFlags |= 3;
- excludeFlags = 536872257;
+ case 313:
+ transformFlags |= 1;
+ excludeFlags = 536870912;
break;
case 115:
case 113:
@@ -24806,7 +25040,7 @@
case 278:
case 213:
case 133:
- transformFlags |= 3;
+ transformFlags |= 1;
break;
case 260:
case 261:
@@ -24820,7 +25054,7 @@
case 268:
case 269:
case 270:
- transformFlags |= 4;
+ transformFlags |= 2;
break;
case 14:
case 15:
@@ -24831,29 +25065,29 @@
case 276:
case 116:
case 214:
- transformFlags |= 192;
+ transformFlags |= 128;
break;
case 10:
if (node.hasExtendedUnicodeEscape) {
- transformFlags |= 192;
+ transformFlags |= 128;
}
break;
case 8:
if (node.numericLiteralFlags & 384) {
- transformFlags |= 192;
+ transformFlags |= 128;
}
break;
case 9:
- transformFlags |= 8;
+ transformFlags |= 4;
break;
case 227:
if (node.awaitModifier) {
- transformFlags |= 8;
+ transformFlags |= 16;
}
- transformFlags |= 192;
+ transformFlags |= 128;
break;
case 207:
- transformFlags |= 8 | 192 | 4194304;
+ transformFlags |= 16 | 128 | 131072;
break;
case 120:
case 135:
@@ -24893,120 +25127,110 @@
case 181:
case 182:
case 247:
- transformFlags = 3;
- excludeFlags = -3;
+ transformFlags = 1;
+ excludeFlags = -2;
break;
case 149:
- transformFlags |= 524288;
- if (subtreeFlags & 8192) {
- transformFlags |= 32768;
- }
+ transformFlags |= 16384;
break;
case 208:
- transformFlags |= 192 | 131072;
+ transformFlags |= 128 | 4096;
break;
case 277:
- transformFlags |= 8 | 262144;
+ transformFlags |= 16 | 8192;
break;
case 98:
- transformFlags |= 192 | 33554432;
- excludeFlags = 536872257;
+ transformFlags |= 128;
+ excludeFlags = 536870912;
break;
case 100:
- transformFlags |= 8192;
+ transformFlags |= 2048;
break;
case 184:
- transformFlags |= 192 | 2097152;
- if (subtreeFlags & 131072) {
- transformFlags |= 8 | 262144;
+ transformFlags |= 128 | 65536;
+ if (subtreeFlags & 4096) {
+ transformFlags |= 16 | 8192;
}
- excludeFlags = 637666625;
+ excludeFlags = 536875008;
break;
case 185:
- transformFlags |= 192 | 2097152;
- excludeFlags = 637666625;
+ transformFlags |= 128 | 65536;
+ excludeFlags = 536875008;
break;
case 186:
- transformFlags |= 192;
+ transformFlags |= 128;
if (node.dotDotDotToken) {
- transformFlags |= 131072;
+ transformFlags |= 4096;
}
break;
case 152:
- transformFlags |= 3 | 4096;
+ transformFlags |= 1 | 1024;
break;
case 188:
- excludeFlags = 638358849;
- if (subtreeFlags & 524288) {
- transformFlags |= 192;
- }
- if (subtreeFlags & 32768) {
- transformFlags |= 8192;
+ excludeFlags = 536896512;
+ if (subtreeFlags & 16384) {
+ transformFlags |= 128;
}
- if (subtreeFlags & 262144) {
- transformFlags |= 8;
+ if (subtreeFlags & 8192) {
+ transformFlags |= 16;
}
break;
case 187:
- case 192:
- excludeFlags = 637666625;
- if (subtreeFlags & 131072) {
- transformFlags |= 192;
- }
+ excludeFlags = 536875008;
break;
case 223:
case 224:
case 225:
case 226:
- if (subtreeFlags & 1048576) {
- transformFlags |= 192;
+ if (subtreeFlags & 32768) {
+ transformFlags |= 128;
}
break;
- case 279:
- if (subtreeFlags & 16384) {
- transformFlags |= 192;
- }
+ case 284:
break;
case 230:
- transformFlags |= 8388608 | 8;
+ transformFlags |= 262144 | 16;
break;
case 228:
case 229:
- transformFlags |= 8388608;
+ transformFlags |= 262144;
break;
}
node.transformFlags = transformFlags | 536870912;
return transformFlags & ~excludeFlags;
}
+ function propagatePropertyNameFlags(node, transformFlags) {
+ return transformFlags | (node.transformFlags & 2048);
+ }
function getTransformFlagsSubtreeExclusions(kind) {
if (kind >= 163 && kind <= 183) {
- return -3;
+ return -2;
}
switch (kind) {
case 191:
case 192:
case 187:
- return 637666625;
+ return 536875008;
case 244:
- return 647001409;
+ return 537168896;
case 151:
- return 637535553;
+ return 536870912;
case 197:
- return 653604161;
+ return 537371648;
case 196:
case 239:
- return 653620545;
+ return 537373696;
case 238:
- return 639894849;
+ return 536944640;
case 240:
case 209:
- return 638121281;
+ return 536888320;
case 157:
- return 653616449;
+ return 537372672;
case 156:
case 158:
case 159:
- return 653616449;
+ return 537372672;
case 120:
case 135:
case 146:
@@ -25024,25 +25248,25 @@
case 162:
case 241:
case 242:
- return -3;
+ return -2;
case 188:
- return 638358849;
+ return 536896512;
case 274:
- return 637797697;
+ return 536879104;
case 184:
case 185:
- return 637666625;
+ return 536875008;
case 194:
case 212:
- case 308:
+ case 313:
case 195:
case 98:
- return 536872257;
+ return 536870912;
case 189:
case 190:
- return 570426689;
+ return 536870912;
default:
- return 637535553;
+ return 536870912;
}
}
ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
@@ -25266,6 +25490,7 @@
var enumCount = 0;
var instantiationDepth = 0;
var constraintDepth = 0;
+ var currentNode;
var emptySymbols = ts.createSymbolTable();
var identityMapper = ts.identity;
var compilerOptions = host.getCompilerOptions();
@@ -25282,8 +25507,14 @@
var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768;
var emitResolver = createResolver();
var nodeBuilder = createNodeBuilder();
+ var globals = ts.createSymbolTable();
var undefinedSymbol = createSymbol(4, "undefined");
undefinedSymbol.declarations = [];
+ var globalThisSymbol = createSymbol(1536, "globalThis", 8);
+ globalThisSymbol.exports = globals;
+ globalThisSymbol.valueDeclaration = ts.createNode(72);
+ globalThisSymbol.valueDeclaration.escapedText = "globalThis";
+ globals.set(globalThisSymbol.escapedName, globalThisSymbol);
var argumentsSymbol = createSymbol(4, "arguments");
var requireSymbol = createSymbol(4, "require");
var apparentArgumentCount;
@@ -25407,11 +25638,13 @@
isContextSensitive: isContextSensitive,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, false);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 0);
},
getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, true);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16);
},
+ getExpandedParameters: getExpandedParameters,
+ hasEffectiveRestParameter: hasEffectiveRestParameter,
getConstantValue: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
return node ? getConstantValue(node) : undefined;
@@ -25471,6 +25704,8 @@
getNeverType: function () { return neverType; },
isSymbolAccessible: isSymbolAccessible,
getObjectFlags: ts.getObjectFlags,
+ isArrayType: isArrayType,
+ isTupleType: isTupleType,
isArrayLikeType: isArrayLikeType,
isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
@@ -25486,9 +25721,9 @@
getAccessibleSymbolChain: getAccessibleSymbolChain,
getTypePredicateOfSignature: getTypePredicateOfSignature,
resolveExternalModuleSymbol: resolveExternalModuleSymbol,
- tryGetThisTypeAt: function (node) {
+ tryGetThisTypeAt: function (node, includeGlobalThis) {
node = ts.getParseTreeNode(node);
- return node && tryGetThisTypeAt(node);
+ return node && tryGetThisTypeAt(node, includeGlobalThis);
},
getTypeArgumentConstraint: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
@@ -25531,10 +25766,10 @@
},
getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
};
- function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) {
+ function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
apparentArgumentCount = argumentCount;
- var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined;
+ var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
apparentArgumentCount = undefined;
return res;
}
@@ -25543,6 +25778,7 @@
var intersectionTypes = ts.createMap();
var literalTypes = ts.createMap();
var indexedAccessTypes = ts.createMap();
+ var conditionalTypes = ts.createMap();
var evolvingArrayTypes = [];
var undefinedProperties = ts.createMap();
var unknownSymbol = createSymbol(4, "unknown");
@@ -25553,9 +25789,9 @@
var errorType = createIntrinsicType(1, "error");
var unknownType = createIntrinsicType(2, "unknown");
var undefinedType = createIntrinsicType(32768, "undefined");
- var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 | 134217728, "undefined");
+ var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768, "undefined", 131072);
var nullType = createIntrinsicType(65536, "null");
- var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 | 134217728, "null");
+ var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536, "null", 131072);
var stringType = createIntrinsicType(4, "string");
var numberType = createIntrinsicType(8, "number");
var bigintType = createIntrinsicType(64, "bigint");
@@ -25579,6 +25815,7 @@
var voidType = createIntrinsicType(16384, "void");
var neverType = createIntrinsicType(131072, "never");
var silentNeverType = createIntrinsicType(131072, "never");
+ var nonInferrableType = createIntrinsicType(131072, "never", 524288);
var implicitNeverType = createIntrinsicType(131072, "never");
var nonPrimitiveType = createIntrinsicType(67108864, "object");
var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
@@ -25593,7 +25830,7 @@
var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
emptyGenericType.instantiations = ts.createMap();
var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
- anyFunctionType.flags |= 536870912;
+ anyFunctionType.objectFlags |= 524288;
var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
@@ -25607,7 +25844,6 @@
var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false);
var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, undefined, 0, false, false);
var enumNumberIndexInfo = createIndexInfo(stringType, true);
- var globals = ts.createSymbolTable();
var amalgamatedDuplicates;
var reverseMappedCache = ts.createMap();
var ambientModulesCache;
@@ -25762,18 +25998,6 @@
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)
@@ -25945,7 +26169,7 @@
err.relatedInformation = err.relatedInformation || [];
if (ts.length(err.relatedInformation) >= 5)
continue;
- addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here));
+ ts.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) {
@@ -26015,7 +26239,7 @@
return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
}
function isGlobalSourceFile(node) {
- return node.kind === 279 && !ts.isExternalOrCommonJsModule(node);
+ return node.kind === 284 && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning) {
@@ -26145,7 +26369,7 @@
if (result = lookup(location.locals, name, meaning)) {
var useResult = true;
if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
- if (meaning & result.flags & 67897832 && lastLocation.kind !== 291) {
+ if (meaning & result.flags & 67897832 && lastLocation.kind !== 296) {
useResult = result.flags & 262144
? lastLocation === location.type ||
lastLocation.kind === 151 ||
@@ -26178,13 +26402,13 @@
}
}
switch (location.kind) {
- case 279:
+ case 284:
if (!ts.isExternalOrCommonJsModule(location))
break;
isInExternalModule = true;
case 244:
var moduleExports = getSymbolOfNode(location).exports;
- if (location.kind === 279 || ts.isAmbientModule(location)) {
+ if (location.kind === 284 || ts.isAmbientModule(location)) {
if (result = moduleExports.get("default")) {
var localSymbol = ts.getLocalSymbolForExportDefault(result);
if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
@@ -26297,12 +26521,12 @@
if (location.parent && location.parent.kind === 151) {
location = location.parent;
}
- if (location.parent && ts.isClassElement(location.parent)) {
+ if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 240)) {
location = location.parent;
}
break;
- case 304:
- case 297:
+ case 309:
+ case 302:
location = ts.getJSDocHost(location);
break;
}
@@ -26317,7 +26541,7 @@
}
if (!result) {
if (lastLocation) {
- ts.Debug.assert(lastLocation.kind === 279);
+ ts.Debug.assert(lastLocation.kind === 284);
if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
return lastLocation.symbol;
}
@@ -26340,7 +26564,8 @@
!checkAndReportErrorForExtendingInterface(errorLocation) &&
!checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
!checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
- !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) {
+ !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
+ !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
var suggestion = void 0;
if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
@@ -26348,7 +26573,7 @@
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));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
}
}
}
@@ -26482,6 +26707,16 @@
}
return false;
}
+ function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
+ if (meaning & (67897832 & ~1920)) {
+ var symbol = resolveSymbol(resolveName(errorLocation, name, ~67897832 & 67220415, undefined, undefined, false));
+ if (symbol && !(symbol.flags & 1920)) {
+ error(errorLocation, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here, ts.unescapeLeadingUnderscores(name));
+ return true;
+ }
+ }
+ return false;
+ }
function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
if (meaning & (67220415 & ~1024)) {
if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") {
@@ -26490,7 +26725,7 @@
}
var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 & ~67220415, undefined, undefined, false));
if (symbol && !(symbol.flags & 1024)) {
- var message = (name === "Promise" || name === "Symbol")
+ var message = isES2015OrLaterConstructorName(name)
? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later
: ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
@@ -26499,6 +26734,18 @@
}
return false;
}
+ function isES2015OrLaterConstructorName(n) {
+ switch (n) {
+ case "Promise":
+ case "Symbol":
+ case "Map":
+ case "WeakMap":
+ case "Set":
+ case "WeakSet":
+ return true;
+ }
+ return false;
+ }
function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
if (meaning & (67220415 & ~1024 & ~67897832)) {
var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~67220415, undefined, undefined, false));
@@ -26540,7 +26787,7 @@
}
}
if (diagnosticMessage) {
- addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
+ ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
}
}
}
@@ -26687,7 +26934,7 @@
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));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
}
}
else {
@@ -26972,21 +27219,13 @@
return undefined;
}
if (moduleNotFoundError) {
- if (ts.pathIsRelative(moduleReference)) {
- var sourceFile_1 = ts.getSourceFileOfNode(location);
- var redirects = sourceFile_1.redirectedReferences;
- if (redirects) {
- var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName));
- for (var _i = 0, _a = [".ts", ".tsx"]; _i < _a.length; _i++) {
- var ext = _a[_i];
- var probePath = normalizedTargetPath + ext;
- if (redirects.indexOf(probePath) >= 0) {
- error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath);
+ if (resolvedModule) {
+ var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
+ if (redirect) {
+ error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
return undefined;
}
}
- }
- }
if (resolutionDiagnostic) {
error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
}
@@ -27048,7 +27287,7 @@
function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) {
var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
if (!dontResolveAlias && symbol) {
- if (!(symbol.flags & (1536 | 3)) && !ts.getDeclarationOfKind(symbol, 279)) {
+ if (!(symbol.flags & (1536 | 3)) && !ts.getDeclarationOfKind(symbol, 284)) {
var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
? "allowSyntheticDefaultImports"
: "esModuleInterop";
@@ -27304,9 +27543,11 @@
result.id = typeCount;
return result;
}
- function createIntrinsicType(kind, intrinsicName) {
+ function createIntrinsicType(kind, intrinsicName, objectFlags) {
+ if (objectFlags === void 0) { objectFlags = 0; }
var type = createType(kind);
type.intrinsicName = intrinsicName;
+ type.objectFlags = objectFlags;
return type;
}
function createBooleanType(trueFalseTypes) {
@@ -27372,7 +27613,7 @@
}
}
switch (location.kind) {
- case 279:
+ case 284:
if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
@@ -27560,10 +27801,10 @@
return node && getSymbolOfNode(node);
}
function hasExternalModuleSymbol(declaration) {
- return ts.isAmbientModule(declaration) || (declaration.kind === 279 && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isAmbientModule(declaration) || (declaration.kind === 284 && ts.isExternalOrCommonJsModule(declaration));
}
function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
- return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 284 && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
var aliasesToMakeVisible;
@@ -27917,8 +28158,8 @@
context.inferTypeParameters = type.root.inferTypeParameters;
var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
context.inferTypeParameters = saveInferTypeParameters;
- var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context);
- var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context);
+ var trueTypeNode = typeToTypeNodeHelper(type.trueType, context);
+ var falseTypeNode = typeToTypeNodeHelper(type.falseType, context);
context.approximateLength += 15;
return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
}
@@ -27996,7 +28237,7 @@
var isNonLocalFunctionSymbol = !!(symbol.flags & 16) &&
(symbol.parent ||
ts.forEach(symbol.declarations, function (declaration) {
- return declaration.parent.kind === 279 || declaration.parent.kind === 245;
+ return declaration.parent.kind === 284 || declaration.parent.kind === 245;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
return (!!(context.flags & 4096) || (context.visitedTypes && context.visitedTypes.has(typeId))) &&
@@ -28035,13 +28276,14 @@
}
function typeReferenceToTypeNode(type) {
var typeArguments = type.typeArguments || ts.emptyArray;
- if (type.target === globalArrayType) {
+ if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
if (context.flags & 2) {
var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
- return ts.createTypeReferenceNode("Array", [typeArgumentNode]);
+ return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
}
var elementType = typeToTypeNodeHelper(typeArguments[0], context);
- return ts.createArrayTypeNode(elementType);
+ var arrayType = ts.createArrayTypeNode(elementType);
+ return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(133, arrayType);
}
else if (type.target.objectFlags & 8) {
if (typeArguments.length > 0) {
@@ -28054,11 +28296,13 @@
ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
ts.createOptionalTypeNode(tupleConstituentNodes[i]);
}
- return ts.createTupleTypeNode(tupleConstituentNodes);
+ var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes);
+ return type.target.readonly ? ts.createTypeOperatorNode(133, tupleTypeNode) : tupleTypeNode;
}
}
if (context.encounteredError || (context.flags & 524288)) {
- return ts.createTupleTypeNode([]);
+ var tupleTypeNode = ts.createTupleTypeNode([]);
+ return type.target.readonly ? ts.createTypeOperatorNode(133, tupleTypeNode) : tupleTypeNode;
}
context.encounteredError = true;
return undefined;
@@ -28215,7 +28459,7 @@
context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
context.enclosingDeclaration = saveEnclosingDeclaration;
var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(56) : undefined;
- if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length) {
+ if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
var signatures = getSignaturesOfType(propertyType, 0);
for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
var signature = signatures_1[_i];
@@ -28342,7 +28586,7 @@
var savedContextFlags = context.flags;
context.flags &= ~512;
var shouldUseGeneratedName = context.flags & 4 &&
- type.symbol.declarations[0] &&
+ type.symbol.declarations && type.symbol.declarations[0] &&
ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
typeParameterShadowsNameInScope(type, context);
var name = shouldUseGeneratedName
@@ -28361,7 +28605,7 @@
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151);
if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
- parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299);
+ parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 304);
}
var parameterType = getTypeOfSymbol(parameterSymbol);
if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
@@ -28503,7 +28747,7 @@
return top;
}
function getSpecifierForModuleSymbol(symbol, context) {
- var file = ts.getDeclarationOfKind(symbol, 279);
+ var file = ts.getDeclarationOfKind(symbol, 284);
if (file && file.moduleName !== undefined) {
return file.moduleName;
}
@@ -28746,7 +28990,7 @@
ts.isExternalModuleAugmentation(node.parent.parent);
}
function isDefaultBindingContext(location) {
- return location.kind === 279 || ts.isAmbientModule(location);
+ return location.kind === 284 || ts.isAmbientModule(location);
}
function getNameOfSymbolFromNameType(symbol, context) {
var nameType = symbol.nameType;
@@ -28812,8 +29056,8 @@
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
- case 297:
- case 304:
+ case 302:
+ case 309:
return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
case 186:
return isDeclarationVisible(node.parent.parent);
@@ -28834,7 +29078,7 @@
}
var parent = getDeclarationContainer(node);
if (!(ts.getCombinedModifierFlags(node) & 1) &&
- !(node.kind !== 248 && parent.kind !== 279 && parent.flags & 4194304)) {
+ !(node.kind !== 248 && parent.kind !== 284 && parent.flags & 4194304)) {
return isGlobalSourceFile(parent);
}
return isDeclarationVisible(parent);
@@ -28868,7 +29112,7 @@
case 253:
return false;
case 150:
- case 279:
+ case 284:
case 247:
return true;
case 254:
@@ -29024,7 +29268,7 @@
if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576), omitKeyType)
&& !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16))
&& isSpreadableProperty(prop)) {
- members.set(prop.escapedName, getSpreadSymbol(prop));
+ members.set(prop.escapedName, getSpreadSymbol(prop, false));
}
}
var stringIndexInfo = getIndexInfoOfType(source, 0);
@@ -29083,13 +29327,7 @@
function getTypeForBindingElement(declaration) {
var pattern = declaration.parent;
var parentType = getTypeForBindingElementParent(pattern.parent);
- if (parentType === errorType) {
- return errorType;
- }
- if (!parentType) {
- return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType;
- }
- if (isTypeAny(parentType)) {
+ if (!parentType || isTypeAny(parentType)) {
return parentType;
}
if (strictNullChecks && declaration.flags & 4194304 && ts.isParameterDeclaration(declaration)) {
@@ -29161,6 +29399,11 @@
if (optional === void 0) { optional = true; }
return strictNullChecks && optional ? getOptionalType(type) : type;
}
+ function isParameterOfContextuallyTypedFunction(node) {
+ return node.kind === 151 &&
+ (node.parent.kind === 196 || node.parent.kind === 197) &&
+ !!getContextualType(node.parent);
+ }
function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 226) {
var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression)));
@@ -29220,14 +29463,14 @@
return containerObjectType;
}
}
- if (declaration.initializer) {
+ if (declaration.initializer && !isParameterOfContextuallyTypedFunction(declaration)) {
var type = checkDeclarationInitializer(declaration);
return addOptionality(type, isOptional);
}
if (ts.isJsxAttribute(declaration)) {
return trueType;
}
- if (ts.isBindingPattern(declaration.name)) {
+ if (ts.isBindingPattern(declaration.name) && !isParameterOfContextuallyTypedFunction(declaration)) {
return getTypeFromBindingPattern(declaration.name, false, true);
}
return undefined;
@@ -29280,7 +29523,7 @@
definedInConstructor = true;
}
}
- var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 | 134217728)); }) ? constructorTypes : types;
+ var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304); }) ? constructorTypes : types;
type = getUnionType(sourceTypes, 2);
}
var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
@@ -29423,7 +29666,7 @@
function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
var members = ts.createSymbolTable();
var stringIndexInfo;
- var objectFlags = 128;
+ var objectFlags = 128 | 262144;
ts.forEach(pattern.elements, function (e) {
var name = e.propertyName || e.name;
if (e.dotDotDotToken) {
@@ -29443,7 +29686,6 @@
members.set(symbol.escapedName, symbol);
});
var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
- result.flags |= 268435456;
result.objectFlags |= objectFlags;
if (includePatternInType) {
result.pattern = pattern;
@@ -29507,7 +29749,13 @@
}
function getTypeOfVariableOrParameterOrProperty(symbol) {
var links = getSymbolLinks(symbol);
- return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol));
+ if (!links.type) {
+ var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
+ if (!links.type) {
+ links.type = type;
+ }
+ }
+ return links.type;
}
function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
if (symbol.flags & 4194304) {
@@ -29536,17 +29784,17 @@
}
return type_1;
}
- if (declaration.kind === 254) {
- return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
- }
if (!pushTypeResolution(symbol, 0)) {
if (symbol.flags & 512) {
return getTypeOfFuncClassEnumModule(symbol);
}
- return errorType;
+ return reportCircularityError(symbol);
}
var type;
- if (ts.isInJSFile(declaration) &&
+ if (declaration.kind === 254) {
+ type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
+ }
+ else if (ts.isInJSFile(declaration) &&
(ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) {
type = getWidenedTypeFromAssignmentDeclaration(symbol);
}
@@ -29597,7 +29845,7 @@
if (symbol.flags & 512) {
return getTypeOfFuncClassEnumModule(symbol);
}
- type = reportCircularityError(symbol);
+ return reportCircularityError(symbol);
}
return type;
}
@@ -29765,11 +30013,12 @@
return links.type;
}
function reportCircularityError(symbol) {
- if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) {
+ var declaration = symbol.valueDeclaration;
+ if (ts.getEffectiveTypeAnnotationNode(declaration)) {
error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
return errorType;
}
- if (noImplicitAny) {
+ if (noImplicitAny && (declaration.kind !== 151 || declaration.initializer)) {
error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
}
return anyType;
@@ -29842,15 +30091,15 @@
case 155:
case 165:
case 166:
- case 289:
+ case 294:
case 239:
case 156:
case 196:
case 197:
case 242:
- case 303:
- case 304:
- case 297:
+ case 308:
+ case 309:
+ case 302:
case 181:
case 175:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -29954,7 +30203,7 @@
ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
}
}
- addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
+ ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
}
return type.resolvedBaseConstructorType = errorType;
}
@@ -29965,7 +30214,7 @@
function getBaseTypes(type) {
if (!type.resolvedBaseTypes) {
if (type.objectFlags & 8) {
- type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))];
+ type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)];
}
else if (type.symbol.flags & (32 | 64)) {
if (type.symbol.flags & 32) {
@@ -30320,6 +30569,8 @@
case 156:
case 155:
case 157:
+ case 158:
+ case 159:
return isThislessFunctionLikeDeclaration(declaration);
}
}
@@ -30568,7 +30819,17 @@
return sig;
}
function cloneSignature(sig) {
- return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, undefined, undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes);
+ var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, undefined, undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes);
+ result.target = sig.target;
+ result.mapper = sig.mapper;
+ return result;
+ }
+ function createUnionSignature(signature, unionSignatures) {
+ var result = cloneSignature(signature);
+ result.unionSignatures = unionSignatures;
+ result.target = undefined;
+ result.mapper = undefined;
+ return result;
}
function getExpandedParameters(sig) {
if (sig.hasRestParameter) {
@@ -30667,9 +30928,8 @@
var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2);
thisParameter = createSymbolWithType(signature.thisParameter, thisType);
}
- s = cloneSignature(signature);
+ s = createUnionSignature(signature, unionSignatures);
s.thisParameter = thisParameter;
- s.unionSignatures = unionSignatures;
}
(result || (result = [])).push(s);
}
@@ -30773,13 +31033,22 @@
function unionSpreadIndexInfos(info1, info2) {
return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
}
- function includeMixinType(type, types, index) {
+ function findMixins(types) {
+ var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1).length > 0; });
+ var mixinFlags = ts.map(types, isMixinConstructorType);
+ if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
+ var firstMixinIndex = mixinFlags.indexOf(true);
+ mixinFlags[firstMixinIndex] = false;
+ }
+ return mixinFlags;
+ }
+ function includeMixinType(type, types, mixinFlags, index) {
var mixedTypes = [];
for (var i = 0; i < types.length; i++) {
if (i === index) {
mixedTypes.push(type);
}
- else if (isMixinConstructorType(types[i])) {
+ else if (mixinFlags[i]) {
mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1)[0]));
}
}
@@ -30791,15 +31060,16 @@
var stringIndexInfo;
var numberIndexInfo;
var types = type.types;
- var mixinCount = ts.countWhere(types, isMixinConstructorType);
+ var mixinFlags = findMixins(types);
+ var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
var _loop_6 = function (i) {
var t = type.types[i];
- if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) {
+ if (!mixinFlags[i]) {
var signatures = getSignaturesOfType(t, 1);
if (signatures.length && mixinCount > 0) {
signatures = ts.map(signatures, function (s) {
var clone = cloneSignature(s);
- clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i);
+ clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
return clone;
});
}
@@ -30839,6 +31109,15 @@
var stringIndexInfo = void 0;
if (symbol.exports) {
members = getExportsOfSymbol(symbol);
+ if (symbol === globalThisSymbol) {
+ var varsOnly_1 = ts.createMap();
+ members.forEach(function (p) {
+ if (!(p.flags & 418)) {
+ varsOnly_1.set(p.escapedName, p);
+ }
+ });
+ members = varsOnly_1;
+ }
}
setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
if (symbol.flags & 32) {
@@ -31105,7 +31384,7 @@
var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
- return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected);
+ return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
});
}
function getAllPossiblePropertiesOfTypes(types) {
@@ -31137,6 +31416,9 @@
return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
}
function getConstraintOfIndexedAccess(type) {
+ return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
+ }
+ function getConstraintFromIndexedAccess(type) {
var objectType = getConstraintOfType(type.objectType) || type.objectType;
if (objectType !== type.objectType) {
var constraint = getIndexedAccessType(objectType, type.indexType, undefined, errorType);
@@ -31149,18 +31431,14 @@
}
function getDefaultConstraintOfConditionalType(type) {
if (!type.resolvedDefaultConstraint) {
- var rootTrueType = type.root.trueType;
- var rootTrueConstraint = !(rootTrueType.flags & 33554432)
- ? rootTrueType
- : (rootTrueType.substitute).flags & 3
- ? rootTrueType.typeVariable
- : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]);
- type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]);
+ var trueConstraint = getInferredTrueTypeFromConditionalType(type);
+ var falseConstraint = type.falseType;
+ type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
}
return type.resolvedDefaultConstraint;
}
function getConstraintOfDistributiveConditionalType(type) {
- if (type.root.isDistributive) {
+ if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
var simplified = getSimplifiedType(type.checkType);
var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
if (constraint && constraint !== type.checkType) {
@@ -31173,9 +31451,12 @@
}
return undefined;
}
- function getConstraintOfConditionalType(type) {
+ function getConstraintFromConditionalType(type) {
return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
}
+ function getConstraintOfConditionalType(type) {
+ return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
+ }
function getUnionConstraintOfIntersection(type, targetIsUnion) {
var constraints;
var hasDisjointDomainType = false;
@@ -31232,14 +31513,27 @@
if (!pushTypeResolution(t, 4)) {
return circularConstraintType;
}
- if (constraintDepth === 50) {
+ if (constraintDepth >= 50) {
+ error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
nonTerminating = true;
return t.immediateBaseConstraint = noConstraintType;
}
constraintDepth++;
var result = computeBaseConstraint(getSimplifiedType(t));
constraintDepth--;
- if (!popTypeResolution() || nonTerminating) {
+ if (!popTypeResolution()) {
+ if (t.flags & 262144) {
+ var errorNode = getConstraintDeclaration(t);
+ if (errorNode) {
+ var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
+ if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
+ }
+ }
+ }
+ result = circularConstraintType;
+ }
+ if (nonTerminating) {
result = circularConstraintType;
}
t.immediateBaseConstraint = result || noConstraintType;
@@ -31281,8 +31575,11 @@
return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined;
}
if (t.flags & 16777216) {
- var constraint = getConstraintOfConditionalType(t);
- return constraint && getBaseConstraint(constraint);
+ var constraint = getConstraintFromConditionalType(t);
+ constraintDepth++;
+ var result = constraint && getBaseConstraint(constraint);
+ constraintDepth--;
+ return result;
}
if (t.flags & 33554432) {
return getBaseConstraint(t.substitute);
@@ -31330,7 +31627,7 @@
var typeVariable = getHomomorphicTypeVariable(type);
if (typeVariable) {
var constraint = getConstraintOfTypeParameter(typeVariable);
- if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) {
+ if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
var mapper = makeUnaryTypeMapper(typeVariable, constraint);
return instantiateType(type, combineTypeMappers(mapper, type.mapper));
}
@@ -31343,7 +31640,7 @@
t.flags & 2097152 ? getApparentTypeOfIntersectionType(t) :
t.flags & 132 ? globalStringType :
t.flags & 296 ? globalNumberType :
- t.flags & 2112 ? getGlobalBigIntType(languageVersion >= 6) :
+ t.flags & 2112 ? getGlobalBigIntType(languageVersion >= 7) :
t.flags & 528 ? globalBooleanType :
t.flags & 12288 ? getGlobalESSymbolType(languageVersion >= 2) :
t.flags & 67108864 ? emptyObjectType :
@@ -31351,7 +31648,7 @@
t;
}
function createUnionOrIntersectionProperty(containingType, name) {
- var props;
+ var propSet = ts.createMap();
var indexTypes;
var isUnion = containingType.flags & 1048576;
var excludeModifiers = isUnion ? 24 : 0;
@@ -31366,7 +31663,10 @@
var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
if (prop && !(modifiers & excludeModifiers)) {
commonFlags &= prop.flags;
- props = ts.appendIfUnique(props, prop);
+ var id = "" + getSymbolId(prop);
+ if (!propSet.has(id)) {
+ propSet.set(id, prop);
+ }
checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) |
(!(modifiers & 24) ? 128 : 0) |
(modifiers & 16 ? 256 : 0) |
@@ -31388,9 +31688,10 @@
}
}
}
- if (!props) {
+ if (!propSet.size) {
return undefined;
}
+ var props = ts.arrayFrom(propSet.values());
if (props.length === 1 && !(checkFlags & 16) && !indexTypes) {
return props[0];
}
@@ -31535,10 +31836,10 @@
return result;
}
function isJSDocOptionalParameter(node) {
- return ts.isInJSFile(node) && (node.type && node.type.kind === 288
+ return ts.isInJSFile(node) && (node.type && node.type.kind === 293
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -31571,7 +31872,7 @@
return false;
}
var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293;
}
function createIdentifierTypePredicate(parameterName, parameterIndex, type) {
return { kind: 1, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
@@ -31783,32 +32084,23 @@
}
}
signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
- createTypePredicateFromTypePredicateNode(type, signature.declaration) :
+ createTypePredicateFromTypePredicateNode(type, signature) :
jsdocPredicate || noTypePredicate;
}
ts.Debug.assert(!!signature.resolvedTypePredicate);
}
return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
}
- function createTypePredicateFromTypePredicateNode(node, func) {
+ function createTypePredicateFromTypePredicateNode(node, signature) {
var parameterName = node.parameterName;
var type = getTypeFromTypeNode(node.type);
if (parameterName.kind === 72) {
- return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type);
+ return createIdentifierTypePredicate(parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), 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 === 72 && param.name.escapedText === parameter.escapedText) {
- return i;
- }
- }
- return -1;
- }
function getReturnTypeOfSignature(signature) {
if (!signature.resolvedReturnType) {
if (!pushTypeResolution(signature, 3)) {
@@ -31880,8 +32172,19 @@
}
return undefined;
}
- function getSignatureInstantiation(signature, typeArguments, isJavascript) {
- return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ if (inferredTypeParameters) {
+ var returnSignature = getSingleCallSignature(getReturnTypeOfSignature(instantiatedSignature));
+ if (returnSignature) {
+ var newReturnSignature = cloneSignature(returnSignature);
+ newReturnSignature.typeParameters = inferredTypeParameters;
+ var newInstantiatedSignature = cloneSignature(instantiatedSignature);
+ newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
+ return newInstantiatedSignature;
+ }
+ }
+ return instantiatedSignature;
}
function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
@@ -32048,10 +32351,10 @@
for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
var type = types_5[_i];
if (!(type.flags & excludeKinds)) {
- result |= type.flags;
+ result |= ts.getObjectFlags(type);
}
}
- return result & 939524096;
+ return result & 917504;
}
function createTypeReference(target, typeArguments) {
var id = getTypeListId(typeArguments);
@@ -32059,7 +32362,7 @@
if (!type) {
type = createObjectType(4, target.symbol);
target.instantiations.set(id, type);
- type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0;
+ type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0;
type.target = target;
type.typeArguments = typeArguments;
}
@@ -32198,7 +32501,7 @@
}
function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
if (symbol.flags & (32 | 64)) {
- if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
+ if (symbol.valueDeclaration && symbol.valueDeclaration.parent && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
if (jsdocType) {
return jsdocType;
@@ -32219,6 +32522,9 @@
}
}
function getSubstitutionType(typeVariable, substitute) {
+ if (substitute.flags & 3) {
+ return typeVariable;
+ }
var result = createType(33554432);
result.typeVariable = typeVariable;
result.substitute = substitute;
@@ -32234,7 +32540,7 @@
}
function getConstrainedTypeVariable(typeVariable, node) {
var constraints;
- while (node && !ts.isStatement(node) && node.kind !== 291) {
+ while (node && !ts.isStatement(node) && node.kind !== 296) {
var parent = node.parent;
if (parent.kind === 175 && node === parent.trueType) {
var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
@@ -32456,20 +32762,20 @@
function createIterableIteratorType(iteratedType) {
return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(true), [iteratedType]);
}
- function createArrayType(elementType) {
- return createTypeFromGenericGlobalType(globalArrayType, [elementType]);
- }
- function createReadonlyArrayType(elementType) {
- return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]);
+ function createArrayType(elementType, readonly) {
+ return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
}
function getTypeFromArrayTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType));
+ links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType), isReadonlyTypeOperator(node.parent));
}
return links.resolvedType;
}
- function createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) {
+ function isReadonlyTypeOperator(node) {
+ return ts.isTypeOperatorNode(node) && node.operator === 133;
+ }
+ function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
var typeParameters;
var properties = [];
var maxLength = hasRestElement ? arity - 1 : arity;
@@ -32478,7 +32784,7 @@
for (var i = 0; i < arity; i++) {
var typeParameter = typeParameters[i] = createTypeParameter();
if (i < maxLength) {
- var property = createSymbol(4 | (i >= minLength ? 16777216 : 0), "" + i);
+ var property = createSymbol(4 | (i >= minLength ? 16777216 : 0), "" + i, readonly ? 8 : 0);
property.type = typeParameter;
properties.push(property);
}
@@ -32508,25 +32814,27 @@
type.declaredNumberIndexInfo = undefined;
type.minLength = minLength;
type.hasRestElement = hasRestElement;
+ type.readonly = readonly;
type.associatedNames = associatedNames;
return type;
}
- function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) {
- var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
+ function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
+ var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
var type = tupleTypes.get(key);
if (!type) {
- tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames));
+ tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames));
}
return type;
}
- function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) {
+ function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) {
if (minLength === void 0) { minLength = elementTypes.length; }
if (hasRestElement === void 0) { hasRestElement = false; }
+ if (readonly === void 0) { readonly = false; }
var arity = elementTypes.length;
if (arity === 1 && hasRestElement) {
- return createArrayType(elementTypes[0]);
+ return createArrayType(elementTypes[0], readonly);
}
- var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames);
+ var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames);
return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
}
function getTypeFromTupleTypeNode(node) {
@@ -32539,7 +32847,7 @@
var type = getTypeFromTypeNode(n);
return n === restElement_1 && getIndexTypeOfType(type, 1) || type;
});
- links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1);
+ links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1, isReadonlyTypeOperator(node.parent));
}
return links.resolvedType;
}
@@ -32548,7 +32856,7 @@
if (tuple.hasRestElement) {
index = Math.min(index, getTypeReferenceArity(type) - 1);
}
- return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index));
+ return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index));
}
function getTypeFromOptionalTypeNode(node) {
var type = getTypeFromTypeNode(node.type);
@@ -32594,12 +32902,14 @@
return addTypesToUnion(typeSet, includes, type.types);
}
if (!(flags & 131072 || flags & 2097152 && isEmptyIntersectionType(type))) {
- includes |= flags & ~939524096;
+ includes |= flags & 1835007;
+ if (flags & 66846720)
+ includes |= 262144;
if (type === wildcardType)
- includes |= 268435456;
+ includes |= 4194304;
if (!strictNullChecks && flags & 98304) {
- if (!(flags & 134217728))
- includes |= 134217728;
+ if (!(ts.getObjectFlags(type) & 131072))
+ includes |= 2097152;
}
else {
var len = typeSet.length;
@@ -32618,17 +32928,6 @@
}
return includes;
}
- function isSubtypeOfAny(source, targets) {
- for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
- var target = targets_1[_i];
- if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1) ||
- !(ts.getObjectFlags(getTargetType(target)) & 1) ||
- isTypeDerivedFrom(source, target))) {
- return true;
- }
- }
- return false;
- }
function isSetOfLiteralsFromSameEnum(types) {
var first = types[0];
if (first.flags & 1024) {
@@ -32643,18 +32942,38 @@
}
return false;
}
- function removeSubtypes(types) {
- if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) {
- return;
+ function removeSubtypes(types, primitivesOnly) {
+ var len = types.length;
+ if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
+ return true;
}
- var i = types.length;
+ var i = len;
+ var count = 0;
while (i > 0) {
i--;
- if (isSubtypeOfAny(types[i], types)) {
+ var source = types[i];
+ for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
+ var target = types_7[_i];
+ if (source !== target) {
+ if (count === 100000) {
+ var estimatedCount = (count / (len - i)) * len;
+ if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
+ error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
+ return false;
+ }
+ }
+ count++;
+ if (isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1) ||
+ !(ts.getObjectFlags(getTargetType(target)) & 1) ||
+ isTypeDerivedFrom(source, target))) {
ts.orderedRemoveItemAt(types, i);
+ break;
+ }
}
}
}
+ return true;
+ }
function removeRedundantLiteralTypes(types, includes) {
var i = types.length;
while (i > 0) {
@@ -32682,25 +33001,27 @@
var includes = addTypesToUnion(typeSet, 0, types);
if (unionReduction !== 0) {
if (includes & 3) {
- return includes & 1 ? includes & 268435456 ? wildcardType : anyType : unknownType;
+ return includes & 1 ? includes & 4194304 ? wildcardType : anyType : unknownType;
}
switch (unionReduction) {
case 1:
- if (includes & 8576 | 512) {
+ if (includes & (2944 | 8192)) {
removeRedundantLiteralTypes(typeSet, includes);
}
break;
case 2:
- removeSubtypes(typeSet);
+ if (!removeSubtypes(typeSet, !(includes & 262144))) {
+ return errorType;
+ }
break;
}
if (typeSet.length === 0) {
- return includes & 65536 ? includes & 134217728 ? nullType : nullWideningType :
- includes & 32768 ? includes & 134217728 ? undefinedType : undefinedWideningType :
+ return includes & 65536 ? includes & 2097152 ? nullType : nullWideningType :
+ includes & 32768 ? includes & 2097152 ? undefinedType : undefinedWideningType :
neverType;
}
}
- return getUnionTypeFromSortedList(typeSet, !(includes & 66994211), aliasSymbol, aliasTypeArguments);
+ return getUnionTypeFromSortedList(typeSet, includes & 66994211 ? 0 : 65536, aliasSymbol, aliasTypeArguments);
}
function getUnionTypePredicate(signatures) {
var first;
@@ -32734,7 +33055,7 @@
? ts.isIdentifierTypePredicate(b) && a.parameterIndex === b.parameterIndex
: !ts.isIdentifierTypePredicate(b);
}
- function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) {
+ function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
if (types.length === 0) {
return neverType;
}
@@ -32744,11 +33065,10 @@
var id = getTypeListId(types);
var type = unionTypes.get(id);
if (!type) {
- var propagatedFlags = getPropagatingFlagsOfTypes(types, 98304);
- type = createType(1048576 | propagatedFlags);
+ type = createType(1048576);
unionTypes.set(id, type);
+ type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, 98304);
type.types = types;
- type.primitiveTypesOnly = primitiveTypesOnly;
type.aliasSymbol = aliasSymbol;
type.aliasTypeArguments = aliasTypeArguments;
}
@@ -32768,16 +33088,16 @@
return addTypesToIntersection(typeSet, includes, type.types);
}
if (isEmptyAnonymousObjectType(type)) {
- if (!(includes & 536870912)) {
- includes |= 536870912;
+ if (!(includes & 8388608)) {
+ includes |= 8388608;
typeSet.push(type);
}
}
else {
- includes |= flags & ~939524096;
+ includes |= flags & 1835007;
if (flags & 3) {
if (type === wildcardType)
- includes |= 268435456;
+ includes |= 4194304;
}
else if ((strictNullChecks || !(flags & 98304)) && !ts.contains(typeSet, type)) {
typeSet.push(type);
@@ -32786,8 +33106,8 @@
return includes;
}
function addTypesToIntersection(typeSet, includes, types) {
- for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
- var type = types_7[_i];
+ for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
+ var type = types_8[_i];
includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
}
return includes;
@@ -32824,14 +33144,14 @@
}
function intersectUnionsOfPrimitiveTypes(types) {
var unionTypes;
- var index = ts.findIndex(types, function (t) { return !!(t.flags & 1048576) && t.primitiveTypesOnly; });
+ var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536); });
if (index < 0) {
return false;
}
var i = index + 1;
while (i < types.length) {
var t = types[i];
- if (t.flags & 1048576 && t.primitiveTypesOnly) {
+ if (ts.getObjectFlags(t) & 65536) {
(unionTypes || (unionTypes = [types[index]])).push(t);
ts.orderedRemoveItemAt(types, i);
}
@@ -32855,7 +33175,7 @@
}
}
}
- types[index] = getUnionTypeFromSortedList(result, true);
+ types[index] = getUnionTypeFromSortedList(result, 65536);
return true;
}
function getIntersectionType(types, aliasSymbol, aliasTypeArguments) {
@@ -32865,7 +33185,7 @@
return neverType;
}
if (includes & 1) {
- return includes & 268435456 ? wildcardType : anyType;
+ return includes & 4194304 ? wildcardType : anyType;
}
if (!strictNullChecks && includes & 98304) {
return includes & 32768 ? undefinedType : nullType;
@@ -32876,7 +33196,7 @@
includes & 4096 && includes & 8192) {
removeRedundantPrimitiveTypes(typeSet, includes);
}
- if (includes & 536870912 && includes & 524288) {
+ if (includes & 8388608 && includes & 524288) {
ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
}
if (typeSet.length === 0) {
@@ -32896,9 +33216,9 @@
var id = getTypeListId(typeSet);
var type = intersectionTypes.get(id);
if (!type) {
- var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 98304);
- type = createType(2097152 | propagatedFlags);
+ type = createType(2097152);
intersectionTypes.set(id, type);
+ type.objectFlags = getPropagatingFlagsOfTypes(typeSet, 98304);
type.types = typeSet;
type.aliasSymbol = aliasSymbol;
type.aliasTypeArguments = aliasTypeArguments;
@@ -32953,7 +33273,7 @@
return neverType;
}
function getLiteralTypeFromProperties(type, include) {
- return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); }));
+ return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
}
function getNonEnumNumberIndexInfo(type) {
var numberIndexInfo = getIndexInfoOfType(type, 1);
@@ -32995,6 +33315,9 @@
? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
: errorType;
break;
+ case 133:
+ links.resolvedType = getTypeFromTypeNode(node.type);
+ break;
}
}
return links.resolvedType;
@@ -33087,7 +33410,10 @@
return anyType;
}
if (accessExpression && !isConstEnumObjectType(objectType)) {
- if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
+ if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418)) {
+ error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
+ }
+ else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
}
@@ -33139,7 +33465,7 @@
: accessNode;
}
function isGenericObjectType(type) {
- return maybeTypeOfKind(type, 58982400 | 134217728);
+ return maybeTypeOfKind(type, 58982400 | 131072);
}
function isGenericIndexType(type) {
return maybeTypeOfKind(type, 58982400 | 4194304);
@@ -33172,12 +33498,15 @@
}
}
if (isGenericMappedType(objectType)) {
- var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
- var templateMapper = combineTypeMappers(objectType.mapper, mapper);
- return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType);
+ return type.simplified = mapType(substituteIndexedMappedType(objectType, type.indexType), getSimplifiedType);
}
return type.simplified = type;
}
+ function substituteIndexedMappedType(objectType, index) {
+ var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
+ var templateMapper = combineTypeMappers(objectType.mapper, mapper);
+ return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
+ }
function getIndexedAccessType(objectType, indexType, accessNode, missingType) {
if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; }
if (objectType === wildcardType || indexType === wildcardType) {
@@ -33246,36 +33575,70 @@
function getActualTypeVariable(type) {
return type.flags & 33554432 ? type.typeVariable : type;
}
+ function isIntersectionEmpty(type1, type2) {
+ return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072);
+ }
function getConditionalType(root, mapper) {
var checkType = instantiateType(root.checkType, mapper);
var extendsType = instantiateType(root.extendsType, mapper);
if (checkType === wildcardType || extendsType === wildcardType) {
return wildcardType;
}
- var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 | 134217728);
+ var trueType = instantiateType(root.trueType, mapper);
+ var falseType = instantiateType(root.falseType, mapper);
+ var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType);
+ var result = conditionalTypes.get(instantiationId);
+ if (result) {
+ return result;
+ }
+ var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType);
+ conditionalTypes.set(instantiationId, newResult);
+ return newResult;
+ }
+ function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) {
+ if (falseType.flags & 131072 && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
+ if (checkType.flags & 1 || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) {
+ return trueType;
+ }
+ else if (isIntersectionEmpty(checkType, extendsType)) {
+ return neverType;
+ }
+ }
+ else if (trueType.flags & 131072 && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
+ if (!(checkType.flags & 1) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) {
+ return neverType;
+ }
+ else if (checkType.flags & 1 || isIntersectionEmpty(checkType, extendsType)) {
+ return falseType;
+ }
+ }
+ var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 | 131072);
var combinedMapper;
if (root.inferTypeParameters) {
var context = createInferenceContext(root.inferTypeParameters, undefined, 0);
if (!checkTypeInstantiable) {
inferTypes(context.inferences, checkType, extendsType, 32 | 64);
}
- combinedMapper = combineTypeMappers(mapper, context);
+ combinedMapper = combineTypeMappers(mapper, context.mapper);
}
var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
- if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 | 134217728)) {
+ if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 | 131072)) {
if (inferredExtendsType.flags & 3) {
- return instantiateType(root.trueType, mapper);
+ return trueType;
}
if (checkType.flags & 1) {
- return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]);
+ return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), falseType]);
}
if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) {
- return instantiateType(root.falseType, mapper);
+ return falseType;
}
if (isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
return instantiateType(root.trueType, combinedMapper || mapper);
}
}
+ return getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType);
+ }
+ function getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType) {
var erasedCheckType = getActualTypeVariable(checkType);
var result = createType(16777216);
result.root = root;
@@ -33283,15 +33646,14 @@
result.extendsType = extendsType;
result.mapper = mapper;
result.combinedMapper = combinedMapper;
+ result.trueType = trueType;
+ result.falseType = falseType;
result.aliasSymbol = root.aliasSymbol;
result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper);
return result;
}
- function getTrueTypeFromConditionalType(type) {
- return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
- }
- function getFalseTypeFromConditionalType(type) {
- return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
+ function getInferredTrueTypeFromConditionalType(type) {
+ return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper || type.mapper));
}
function getInferTypeParameters(node) {
var result;
@@ -33453,7 +33815,7 @@
function isNonGenericObjectType(type) {
return !!(type.flags & 524288) && !isGenericMappedType(type);
}
- function getSpreadType(left, right, symbol, typeFlags, objectFlags) {
+ function getSpreadType(left, right, symbol, objectFlags, readonly) {
if (left.flags & 1 || right.flags & 1) {
return anyType;
}
@@ -33467,10 +33829,10 @@
return left;
}
if (left.flags & 1048576) {
- return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); });
+ return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
}
if (right.flags & 1048576) {
- return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); });
+ return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
}
if (right.flags & (528 | 296 | 2112 | 132 | 1056 | 67108864 | 4194304)) {
return left;
@@ -33483,7 +33845,7 @@
var types = left.types;
var lastLeft = types[types.length - 1];
if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
- return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)]));
+ return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
}
}
return getIntersectionType([left, right]);
@@ -33506,7 +33868,7 @@
skippedPrivateMembers.set(rightProp.escapedName, true);
}
else if (isSpreadableProperty(rightProp)) {
- members.set(rightProp.escapedName, getSpreadSymbol(rightProp));
+ members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
}
}
for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
@@ -33530,37 +33892,32 @@
}
}
else {
- members.set(leftProp.escapedName, getSpreadSymbol(leftProp));
+ members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
}
}
- var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo));
- spread.flags |= 268435456 | typeFlags;
- spread.objectFlags |= 128 | 1024 | objectFlags;
+ var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
+ spread.objectFlags |= 128 | 262144 | 1024 | objectFlags;
return spread;
}
function isSpreadableProperty(prop) {
return !(prop.flags & (8192 | 32768 | 65536)) ||
!prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); });
}
- function getSpreadSymbol(prop) {
- var isReadonly = isReadonlySymbol(prop);
+ function getSpreadSymbol(prop, readonly) {
var isSetonlyAccessor = prop.flags & 65536 && !(prop.flags & 32768);
- if (!isReadonly && !isSetonlyAccessor) {
+ if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
return prop;
}
var flags = 4 | (prop.flags & 16777216);
- var result = createSymbol(flags, prop.escapedName);
+ var result = createSymbol(flags, prop.escapedName, readonly ? 8 : 0);
result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
result.declarations = prop.declarations;
result.nameType = prop.nameType;
result.syntheticOrigin = prop;
return result;
}
- function getNonReadonlyIndexSignature(index) {
- if (index && index.isReadonly) {
- return createIndexInfo(index.type, false, index.declaration);
- }
- return index;
+ function getIndexInfoWithReadonly(info, readonly) {
+ return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
}
function createLiteralType(flags, value, symbol) {
var type = createType(flags);
@@ -33644,8 +34001,8 @@
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 120:
- case 284:
- case 285:
+ case 289:
+ case 290:
return anyType;
case 143:
return unknownType;
@@ -33692,23 +34049,23 @@
return getTypeFromUnionTypeNode(node);
case 174:
return getTypeFromIntersectionTypeNode(node);
- case 286:
+ case 291:
return getTypeFromJSDocNullableTypeNode(node);
- case 288:
+ case 293:
return addOptionality(getTypeFromTypeNode(node.type));
case 177:
case 172:
- case 287:
- case 283:
+ case 292:
+ case 288:
return getTypeFromTypeNode(node.type);
- case 290:
+ case 295:
return getTypeFromJSDocVariadicType(node);
case 165:
case 166:
case 168:
- case 292:
- case 289:
- case 293:
+ case 297:
+ case 294:
+ case 298:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 179:
return getTypeFromTypeOperatorNode(node);
@@ -33778,16 +34135,8 @@
function createTypeEraser(sources) {
return createTypeMapper(sources, undefined);
}
- function createBackreferenceMapper(typeParameters, index) {
- return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; };
- }
- function isInferenceContext(mapper) {
- return !!mapper.typeParameters;
- }
- function cloneTypeMapper(mapper) {
- return mapper && isInferenceContext(mapper) ?
- createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1, mapper.compareTypes, mapper.inferences) :
- mapper;
+ function createBackreferenceMapper(context, index) {
+ return function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? emptyObjectType : t; };
}
function combineTypeMappers(mapper1, mapper2) {
if (!mapper1)
@@ -33855,7 +34204,7 @@
symbol = links.target;
mapper = combineTypeMappers(links.mapper, mapper);
}
- var result = createSymbol(symbol.flags, symbol.escapedName, 1 | ts.getCheckFlags(symbol) & (2048 | 8192 | 16384));
+ var result = createSymbol(symbol.flags, symbol.escapedName, 1 | ts.getCheckFlags(symbol) & (8 | 2048 | 8192 | 16384));
result.declarations = symbol.declarations;
result.parent = symbol.parent;
result.target = symbol;
@@ -33941,7 +34290,7 @@
function getHomomorphicTypeVariable(type) {
var constraintType = getConstraintTypeFromMappedType(type);
if (constraintType.flags & 4194304) {
- var typeVariable = constraintType.type;
+ var typeVariable = getActualTypeVariable(constraintType.type);
if (typeVariable.flags & 262144) {
return typeVariable;
}
@@ -33953,26 +34302,27 @@
if (typeVariable) {
var mappedTypeVariable = instantiateType(typeVariable, mapper);
if (typeVariable !== mappedTypeVariable) {
- if (type.instantiating) {
- return errorType;
- }
- type.instantiating = true;
- var result = mapType(mappedTypeVariable, function (t) {
- if (t.flags & (3 | 58982400 | 524288 | 2097152) && t !== wildcardType) {
+ return mapType(mappedTypeVariable, function (t) {
+ if (t.flags & (3 | 58982400 | 524288 | 2097152) && t !== wildcardType && t !== errorType) {
var replacementMapper = createReplacementMapper(typeVariable, t, mapper);
- return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) :
- isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) :
+ return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
instantiateAnonymousType(type, replacementMapper);
}
return t;
});
- type.instantiating = false;
- return result;
}
}
return instantiateAnonymousType(type, mapper);
}
+ function getModifiedReadonlyState(state, modifiers) {
+ return modifiers & 1 ? true : modifiers & 2 ? false : state;
+ }
+ function instantiateMappedArrayType(arrayType, mappedType, mapper) {
+ var elementType = instantiateMappedTypeTemplate(mappedType, numberType, true, mapper);
+ return elementType === errorType ? errorType :
+ createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
+ }
function instantiateMappedTupleType(tupleType, mappedType, mapper) {
var minLength = tupleType.target.minLength;
var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) {
@@ -33982,7 +34332,9 @@
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);
+ var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
+ return ts.contains(elementTypes, errorType) ? errorType :
+ createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames);
}
function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key]));
@@ -34038,6 +34390,7 @@
return type;
}
if (instantiationDepth === 50) {
+ error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
return errorType;
}
instantiationDepth++;
@@ -34086,7 +34439,17 @@
return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
}
if (flags & 33554432) {
- return instantiateType(type.typeVariable, mapper);
+ var maybeVariable = instantiateType(type.typeVariable, mapper);
+ if (maybeVariable.flags & 8650752) {
+ return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
+ }
+ else {
+ var sub = instantiateType(type.substitute, mapper);
+ if (sub.flags & 3 || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
+ return maybeVariable;
+ }
+ return sub;
+ }
}
return type;
}
@@ -34095,8 +34458,15 @@
type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
}
function getRestrictiveInstantiation(type) {
- return type.flags & (131068 | 3 | 131072) ? type :
- type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper));
+ if (type.flags & (131068 | 3 | 131072)) {
+ return type;
+ }
+ if (type.restrictiveInstantiation) {
+ return type.restrictiveInstantiation;
+ }
+ type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
+ type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
+ return type.restrictiveInstantiation;
}
function instantiateIndexInfo(info, mapper) {
return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
@@ -34263,7 +34633,7 @@
var resultObj = {};
checkTypeAssignableTo(source, target, node, headMessage, undefined, resultObj);
var diagnostic = resultObj.error;
- addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
return true;
}
}
@@ -34296,7 +34666,7 @@
checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, undefined, undefined, resultObj);
if (resultObj.error) {
if (target.symbol && ts.length(target.symbol.declarations)) {
- addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
+ ts.addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
}
return true;
}
@@ -34334,13 +34704,13 @@
undefined;
if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
issuedElaboration = true;
- addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
+ ts.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))) {
var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
- addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
+ ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
}
}
}
@@ -34410,7 +34780,7 @@
case 270:
return { errorNode: child, innerExpression: child.expression, nameType: nameType };
case 11:
- if (child.containsOnlyWhiteSpaces) {
+ if (child.containsOnlyTriviaWhiteSpaces) {
break;
}
return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() };
@@ -34431,7 +34801,7 @@
var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
var childrenNameType = getLiteralType(childrenPropName);
var childrenTargetType = getIndexedAccessType(target, childrenNameType);
- var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyWhiteSpaces; });
+ var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
if (!ts.length(validChildren)) {
return result;
}
@@ -34515,7 +34885,7 @@
if (isTupleLikeType(source)) {
return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation);
}
- var tupleizedType = checkArrayLiteral(node, 3, true);
+ var tupleizedType = checkArrayLiteral(node, 1, true);
if (isTupleLikeType(tupleizedType)) {
return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation);
}
@@ -34575,10 +34945,18 @@
function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
return compareSignaturesRelated(source, target, 0, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0;
}
+ function isAnySignature(s) {
+ return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
+ s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
+ isTypeAny(getReturnTypeOfSignature(s));
+ }
function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) {
if (source === target) {
return -1;
}
+ if (isAnySignature(target)) {
+ return -1;
+ }
var targetCount = getParameterCount(target);
if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) {
return 0;
@@ -34644,7 +35022,7 @@
if (targetTypePredicate) {
var sourceTypePredicate = getTypePredicateOfSignature(source);
if (sourceTypePredicate) {
- result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes);
+ result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
}
else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
if (reportErrors) {
@@ -34660,7 +35038,7 @@
}
return result;
}
- function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) {
+ function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
if (source.kind !== target.kind) {
if (reportErrors) {
errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
@@ -34669,12 +35047,9 @@
return 0;
}
if (source.kind === 1) {
- var targetPredicate = target;
- var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0);
- var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0);
- if (sourceIndex !== targetIndex) {
+ if (source.parameterIndex !== target.parameterIndex) {
if (reportErrors) {
- errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName);
+ errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
}
return 0;
@@ -34859,7 +35234,7 @@
}
var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
if (relatedInfo) {
- addRelatedInfo.apply(void 0, [diag].concat(relatedInfo));
+ ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInfo));
}
if (errorOutputContainer) {
errorOutputContainer.error = diag;
@@ -35380,8 +35755,8 @@
if (source.root.isDistributive === target.root.isDistributive) {
if (result_3 = isRelatedTo(source.checkType, target.checkType, false)) {
if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, false)) {
- if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) {
- if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) {
+ if (result_3 &= isRelatedTo(source.trueType, target.trueType, false)) {
+ if (result_3 &= isRelatedTo(source.falseType, target.falseType, false)) {
return result_3;
}
}
@@ -35396,16 +35771,16 @@
}
var result;
var originalErrorInfo;
+ var varianceCheckFailed = false;
var saveErrorInfo = errorInfo;
if (source.flags & (524288 | 16777216) && source.aliasSymbol &&
source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
!(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
var variances = getAliasVariances(source.aliasSymbol);
- if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) {
- return result;
+ var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances);
+ if (varianceResult !== undefined) {
+ return varianceResult;
}
- originalErrorInfo = errorInfo;
- errorInfo = saveErrorInfo;
}
if (target.flags & 262144) {
if (ts.getObjectFlags(source) & 32 && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) {
@@ -35451,8 +35826,16 @@
template.indexType === getTypeParameterFromMappedType(target)) {
return -1;
}
- if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) {
- var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target));
+ if (!isGenericMappedType(source)) {
+ var targetConstraint = getConstraintTypeFromMappedType(target);
+ var sourceKeys_1 = getIndexType(source);
+ var hasOptionalUnionKeys = modifiers & 4 && targetConstraint.flags & 1048576;
+ var filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, function (t) { return !!isRelatedTo(t, sourceKeys_1); }) : undefined;
+ if (hasOptionalUnionKeys
+ ? !(filteredByApplicability.flags & 131072)
+ : isRelatedTo(targetConstraint, sourceKeys_1)) {
+ var indexingType = hasOptionalUnionKeys ? filteredByApplicability : getTypeParameterFromMappedType(target);
+ var indexedAccessType = getIndexedAccessType(source, indexingType);
var templateType = getTemplateTypeFromMappedType(target);
if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
return result;
@@ -35462,6 +35845,7 @@
errorInfo = saveErrorInfo;
}
}
+ }
if (source.flags & 8650752) {
if (source.flags & 8388608 && target.flags & 8388608) {
if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
@@ -35498,8 +35882,8 @@
if (target.flags & 16777216) {
if (isTypeIdenticalTo(source.extendsType, target.extendsType) &&
(isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
- if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) {
- result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
+ if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) {
+ result &= isRelatedTo(source.falseType, target.falseType, reportErrors);
}
if (result) {
errorInfo = saveErrorInfo;
@@ -35544,20 +35928,17 @@
if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target &&
!(ts.getObjectFlags(source) & 8192 || ts.getObjectFlags(target) & 8192)) {
var variances = getVariances(source.target);
- if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) {
- return result;
- }
- if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) {
- if (!(reportErrors && ts.some(variances, function (v) { return v === 0; }))) {
- return 0;
- }
- originalErrorInfo = errorInfo;
- errorInfo = saveErrorInfo;
+ var varianceResult = relateVariances(source.typeArguments, target.typeArguments, variances);
+ if (varianceResult !== undefined) {
+ return varianceResult;
}
}
- else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) {
+ else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
return isRelatedTo(getIndexTypeOfType(source, 1) || anyType, getIndexTypeOfType(target, 1) || anyType, reportErrors);
}
+ else if (relation === subtypeRelation && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 && !isEmptyObjectType(source)) {
+ return 0;
+ }
if (source.flags & (524288 | 2097152) && target.flags & 524288) {
var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive;
result = propertiesRelatedTo(source, target, reportStructuralErrors);
@@ -35573,17 +35954,36 @@
}
}
}
- if (result) {
- if (!originalErrorInfo) {
- errorInfo = saveErrorInfo;
+ if (varianceCheckFailed && result) {
+ errorInfo = originalErrorInfo || errorInfo || saveErrorInfo;
+ }
+ else if (result) {
return result;
}
- errorInfo = originalErrorInfo;
}
}
+ return 0;
+ function isNonGeneric(type) {
+ if (relation === identityRelation) {
+ return isRelatedTo(type, getPermissiveInstantiation(type)) === -1;
+ }
+ return isTypeIdenticalTo(type, getPermissiveInstantiation(type));
+ }
+ function relateVariances(sourceTypeArguments, targetTypeArguments, variances) {
+ if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors)) {
+ return result;
}
+ var allowStructuralFallback = (targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances)) || isNonGeneric(source) || isNonGeneric(target);
+ varianceCheckFailed = !allowStructuralFallback;
+ if (variances !== ts.emptyArray && !allowStructuralFallback) {
+ if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return v === 0; }))) {
return 0;
}
+ originalErrorInfo = errorInfo;
+ errorInfo = saveErrorInfo;
+ }
+ }
+ }
function mappedTypeRelatedTo(source, target, reportErrors) {
var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
@@ -36007,17 +36407,14 @@
return variances;
}
function getVariances(type) {
- if (!strictFunctionTypes) {
- return ts.emptyArray;
- }
- if (type === globalArrayType || type === globalReadonlyArrayType) {
+ if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8) {
return ts.emptyArray;
}
return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
}
- function hasCovariantVoidArgument(type, variances) {
+ function hasCovariantVoidArgument(typeArguments, variances) {
for (var i = 0; i < variances.length; i++) {
- if (variances[i] === 1 && type.typeArguments[i].flags & 16384) {
+ if (variances[i] === 1 && typeArguments[i].flags & 16384) {
return true;
}
}
@@ -36205,8 +36602,8 @@
}
function literalTypesWithSameBaseType(types) {
var commonBaseType;
- for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
- var t = types_8[_i];
+ for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
+ var t = types_9[_i];
var baseType = getBaseTypeOfLiteralType(t);
if (!commonBaseType) {
commonBaseType = baseType;
@@ -36235,7 +36632,7 @@
return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
}
function isArrayType(type) {
- return !!(ts.getObjectFlags(type) & 4) && type.target === globalArrayType;
+ return !!(ts.getObjectFlags(type) & 4) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
}
function isReadonlyArrayType(type) {
return !!(ts.getObjectFlags(type) & 4) && type.target === globalReadonlyArrayType;
@@ -36244,8 +36641,7 @@
return isArrayType(type) && type.typeArguments ? type.typeArguments[0] : undefined;
}
function isArrayLikeType(type) {
- return ts.getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) ||
- !(type.flags & 98304) && isTypeAssignableTo(type, anyReadonlyArrayType);
+ return isArrayType(type) || !(type.flags & 98304) && isTypeAssignableTo(type, anyReadonlyArrayType);
}
function isEmptyArrayLiteralType(type) {
var elementType = isArrayType(type) ? type.typeArguments[0] : undefined;
@@ -36326,8 +36722,8 @@
}
function getFalsyFlagsOfTypes(types) {
var result = 0;
- for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
- var t = types_9[_i];
+ for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
+ var t = types_10[_i];
result |= getFalsyFlags(t);
}
return result;
@@ -36423,7 +36819,7 @@
var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
regularNew.flags = resolved.flags;
- regularNew.objectFlags |= 128 | (ts.getObjectFlags(resolved) & 16384);
+ regularNew.objectFlags |= resolved.objectFlags & ~32768;
type.regularType = regularNew;
return regularNew;
}
@@ -36500,14 +36896,14 @@
var stringIndexInfo = getIndexInfoOfType(type, 0);
var numberIndexInfo = getIndexInfoOfType(type, 1);
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);
+ result.objectFlags |= (ts.getObjectFlags(type) & (16384 | 524288));
return result;
}
function getWidenedType(type) {
return getWidenedTypeWithContext(type, undefined);
}
function getWidenedTypeWithContext(type, context) {
- if (type.flags & 402653184) {
+ if (ts.getObjectFlags(type) & 393216) {
if (type.flags & 98304) {
return anyType;
}
@@ -36530,7 +36926,7 @@
}
function reportWideningErrorsInType(type) {
var errorReported = false;
- if (type.flags & 134217728) {
+ if (ts.getObjectFlags(type) & 131072) {
if (type.flags & 1048576) {
if (ts.some(type.types, isEmptyObjectType)) {
errorReported = true;
@@ -36556,7 +36952,7 @@
for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
var p = _e[_d];
var t = getTypeOfSymbol(p);
- if (t.flags & 134217728) {
+ if (ts.getObjectFlags(t) & 131072) {
if (!reportWideningErrorsInType(t)) {
error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
}
@@ -36600,7 +36996,7 @@
return;
}
break;
- case 289:
+ case 294:
error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
return;
case 239:
@@ -36627,13 +37023,13 @@
errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
}
function reportErrorsFromWidening(declaration, type) {
- if (produceDiagnostics && noImplicitAny && type.flags & 134217728) {
+ if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072) {
if (!reportWideningErrorsInType(type)) {
reportImplicitAny(declaration, type);
}
}
}
- function forEachMatchingParameterType(source, target, callback) {
+ function applyToParameterTypes(source, target, callback) {
var sourceCount = getParameterCount(source);
var targetCount = getParameterCount(target);
var sourceRestType = getEffectiveRestType(source);
@@ -36654,25 +37050,55 @@
callback(getRestTypeAtPosition(source, paramCount), targetRestType);
}
}
- function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) {
- var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo);
- var context = mapper;
- context.typeParameters = typeParameters;
- context.signature = signature;
- context.inferences = inferences;
- context.flags = flags;
- context.compareTypes = compareTypes || compareTypesAssignable;
+ function applyToReturnTypes(source, target, callback) {
+ var sourceTypePredicate = getTypePredicateOfSignature(source);
+ var targetTypePredicate = getTypePredicateOfSignature(target);
+ if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind &&
+ (sourceTypePredicate.kind === 0 || sourceTypePredicate.parameterIndex === targetTypePredicate.parameterIndex)) {
+ callback(sourceTypePredicate.type, targetTypePredicate.type);
+ }
+ else {
+ callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
+ }
+ }
+ function createInferenceContext(typeParameters, signature, flags, compareTypes) {
+ return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
+ }
+ function cloneInferenceContext(context, extraFlags) {
+ if (extraFlags === void 0) { extraFlags = 0; }
+ return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
+ }
+ function cloneInferredPartOfContext(context) {
+ var inferences = ts.filter(context.inferences, hasInferenceCandidates);
+ return inferences.length ?
+ createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
+ undefined;
+ }
+ function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
+ var context = {
+ inferences: inferences,
+ signature: signature,
+ flags: flags,
+ compareTypes: compareTypes,
+ mapper: function (t) { return mapToInferredType(context, t, true); },
+ nonFixingMapper: function (t) { return mapToInferredType(context, t, false); },
+ };
return context;
- function mapper(t) {
+ }
+ function mapToInferredType(context, t, fix) {
+ var inferences = context.inferences;
for (var i = 0; i < inferences.length; i++) {
- if (t === inferences[i].typeParameter) {
- inferences[i].isFixed = true;
+ var inference = inferences[i];
+ if (t === inference.typeParameter) {
+ if (fix && !inference.isFixed) {
+ inference.isFixed = true;
+ inference.inferredType = undefined;
+ }
return getInferredType(context, i);
}
}
return t;
}
- }
function createInferenceInfo(typeParameter) {
return {
typeParameter: typeParameter,
@@ -36695,6 +37121,9 @@
isFixed: inference.isFixed
};
}
+ function getMapperFromContext(context) {
+ return context && context.mapper;
+ }
function couldContainTypeVariables(type) {
var objectFlags = ts.getObjectFlags(type);
return !!(type.flags & 63176704 ||
@@ -36741,27 +37170,17 @@
return type;
}
function createReverseMappedType(source, target, constraint) {
- var properties = getPropertiesOfType(source);
- if (properties.length === 0 && !getIndexInfoOfType(source, 0)) {
- return undefined;
- }
- for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
- var prop = properties_3[_i];
- if (getTypeOfSymbol(prop).flags & 536870912) {
+ if (ts.getObjectFlags(source) & 524288 || getPropertiesOfType(source).length === 0 && !getIndexInfoOfType(source, 0)) {
return undefined;
}
- }
if (isArrayType(source)) {
- return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint));
- }
- if (isReadonlyArrayType(source)) {
- return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint));
+ return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint), isReadonlyArrayType(source));
}
if (isTupleType(source)) {
var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); });
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);
+ return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, source.target.associatedNames);
}
var reversed = createObjectType(2048 | 16, undefined);
reversed.source = source;
@@ -36780,16 +37199,16 @@
return getTypeFromInference(inference);
}
function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
- var properties, _i, properties_4, targetProp, sourceProp, targetType, sourceType;
+ var properties, _i, properties_3, targetProp, sourceProp, targetType, sourceType;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
properties = target.flags & 2097152 ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target);
- _i = 0, properties_4 = properties;
+ _i = 0, properties_3 = properties;
_a.label = 1;
case 1:
- if (!(_i < properties_4.length)) return [3, 6];
- targetProp = properties_4[_i];
+ if (!(_i < properties_3.length)) return [3, 6];
+ targetProp = properties_3[_i];
if (!(requireOptionalProperties || !(targetProp.flags & 16777216))) return [3, 5];
sourceProp = getPropertyOfType(source, targetProp.escapedName);
if (!!sourceProp) return [3, 3];
@@ -36831,11 +37250,11 @@
inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
emptyObjectType;
}
- function inferTypes(inferences, originalSource, originalTarget, priority) {
+ function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
if (priority === void 0) { priority = 0; }
+ if (contravariant === void 0) { contravariant = false; }
var symbolStack;
var visited;
- var contravariant = false;
var bivariant = false;
var propagationType;
var allowComplexConstraintInference = true;
@@ -36888,7 +37307,7 @@
}
}
if (target.flags & 8650752) {
- if (source.flags & 536870912 || source === silentNeverType || (priority & 8 && (source === autoType || source === autoArrayType))) {
+ if (ts.getObjectFlags(source) & 524288 || source === silentNeverType || (priority & 8 && (source === autoType || source === autoArrayType))) {
return;
}
var inference = getInferenceInfoForType(target);
@@ -36897,19 +37316,25 @@
if (inference.priority === undefined || priority < inference.priority) {
inference.candidates = undefined;
inference.contraCandidates = undefined;
+ inference.topLevel = true;
inference.priority = priority;
}
if (priority === inference.priority) {
var candidate = propagationType || source;
if (contravariant && !bivariant) {
- inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate);
+ if (!ts.contains(inference.contraCandidates, candidate)) {
+ inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
+ inference.inferredType = undefined;
}
- else {
- inference.candidates = ts.appendIfUnique(inference.candidates, candidate);
+ }
+ else if (!ts.contains(inference.candidates, candidate)) {
+ inference.candidates = ts.append(inference.candidates, candidate);
+ inference.inferredType = undefined;
}
}
- if (!(priority & 8) && target.flags & 262144 && !isTypeParameterAtTopLevel(originalTarget, target)) {
+ if (!(priority & 8) && target.flags & 262144 && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
inference.topLevel = false;
+ inference.inferredType = undefined;
}
}
return;
@@ -36930,6 +37355,9 @@
}
}
}
+ else if (target.flags & 33554432) {
+ inferFromTypes(source, target.typeVariable);
+ }
if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target) {
var sourceTypes = source.typeArguments || ts.emptyArray;
var targetTypes = target.typeArguments || ts.emptyArray;
@@ -36965,37 +37393,40 @@
else if (source.flags & 16777216 && target.flags & 16777216) {
inferFromTypes(source.checkType, target.checkType);
inferFromTypes(source.extendsType, target.extendsType);
- inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
- inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
+ inferFromTypes(source.trueType, target.trueType);
+ inferFromTypes(source.falseType, target.falseType);
}
- else if (target.flags & 16777216) {
- inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]));
+ else if (target.flags & 16777216 && !contravariant) {
+ inferFromTypes(source, target.trueType);
+ inferFromTypes(source, target.falseType);
}
else if (target.flags & 3145728) {
- var targetTypes = target.types;
var typeVariableCount = 0;
- var typeVariable = void 0;
- for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) {
- var t = targetTypes_3[_d];
+ for (var _d = 0, _e = target.types; _d < _e.length; _d++) {
+ var t = _e[_d];
if (getInferenceInfoForType(t)) {
- typeVariable = t;
typeVariableCount++;
}
else {
inferFromTypes(source, t);
}
}
- if (typeVariableCount === 1) {
+ if (target.flags & 1048576 ? typeVariableCount !== 0 : typeVariableCount === 1) {
var savePriority = priority;
priority |= 1;
- inferFromTypes(source, typeVariable);
+ for (var _f = 0, _g = target.types; _f < _g.length; _f++) {
+ var t = _g[_f];
+ if (getInferenceInfoForType(t)) {
+ inferFromTypes(source, t);
+ }
+ }
priority = savePriority;
}
}
else if (source.flags & 1048576) {
var sourceTypes = source.types;
- for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) {
- var sourceType = sourceTypes_3[_e];
+ for (var _h = 0, sourceTypes_3 = sourceTypes; _h < sourceTypes_3.length; _h++) {
+ var sourceType = sourceTypes_3[_h];
inferFromTypes(sourceType, target);
}
}
@@ -37059,12 +37490,12 @@
}
return undefined;
}
- function inferFromMappedTypeConstraint(source, target, constraintType) {
+ function inferToMappedType(source, target, constraintType) {
if (constraintType.flags & 1048576) {
var result = false;
for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
var type = _a[_i];
- result = inferFromMappedTypeConstraint(source, target, type) || result;
+ result = inferToMappedType(source, target, type) || result;
}
return result;
}
@@ -37086,6 +37517,10 @@
priority |= 4;
inferFromTypes(getIndexType(source), constraintType);
priority = savePriority;
+ var extendedConstraint = getConstraintOfType(constraintType);
+ if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
+ return true;
+ }
var valueTypes = ts.compact([
getIndexTypeOfType(source, 0),
getIndexTypeOfType(source, 1)
@@ -37102,7 +37537,7 @@
}
if (ts.getObjectFlags(target) & 32) {
var constraintType = getConstraintTypeFromMappedType(target);
- if (inferFromMappedTypeConstraint(source, target, constraintType)) {
+ if (inferToMappedType(source, target, constraintType)) {
return;
}
}
@@ -37114,11 +37549,11 @@
}
}
function inferFromProperties(source, target) {
- if (isTupleType(source)) {
+ if (isArrayType(source) || isTupleType(source)) {
if (isTupleType(target)) {
- var sourceLength = getLengthOfTupleType(source);
+ var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0;
var targetLength = getLengthOfTupleType(target);
- var sourceRestType = getRestTypeOfTupleType(source);
+ var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source);
var targetRestType = getRestTypeOfTupleType(target);
var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
for (var i = 0; i < fixedLength; i++) {
@@ -37141,8 +37576,8 @@
}
}
var properties = getPropertiesOfObjectType(target);
- for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
- var targetProp = properties_5[_i];
+ for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) {
+ var targetProp = properties_4[_i];
var sourceProp = getPropertyOfType(source, targetProp.escapedName);
if (sourceProp) {
inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
@@ -37155,7 +37590,7 @@
var sourceLen = sourceSignatures.length;
var targetLen = targetSignatures.length;
var len = sourceLen < targetLen ? sourceLen : targetLen;
- var skipParameters = !!(source.flags & 536870912);
+ var skipParameters = !!(ts.getObjectFlags(source) & 524288);
for (var i = 0; i < len; i++) {
inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters);
}
@@ -37165,17 +37600,10 @@
var saveBivariant = bivariant;
var kind = target.declaration ? target.declaration.kind : 0;
bivariant = bivariant || kind === 156 || kind === 155 || kind === 157;
- forEachMatchingParameterType(source, target, inferFromContravariantTypes);
+ applyToParameterTypes(source, target, inferFromContravariantTypes);
bivariant = saveBivariant;
}
- var sourceTypePredicate = getTypePredicateOfSignature(source);
- var targetTypePredicate = getTypePredicateOfSignature(target);
- if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) {
- inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type);
- }
- else {
- inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
- }
+ applyToReturnTypes(source, target, inferFromTypes);
}
function inferFromIndexTypes(source, target) {
var targetStringIndexType = getIndexTypeOfType(target, 0);
@@ -37198,8 +37626,8 @@
}
}
function typeIdenticalToSomeType(type, types) {
- for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
- var t = types_10[_i];
+ for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
+ var t = types_11[_i];
if (isTypeIdenticalTo(t, type)) {
return true;
}
@@ -37271,7 +37699,7 @@
else {
var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
if (defaultType) {
- inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
}
else {
inferredType = getDefaultTypeArgumentType(!!(context.flags & 2));
@@ -37284,7 +37712,7 @@
inference.inferredType = inferredType;
var constraint = getConstraintOfTypeParameter(inference.typeParameter);
if (constraint) {
- var instantiatedConstraint = instantiateType(constraint, context);
+ var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
inference.inferredType = inferredType = instantiatedConstraint;
}
@@ -37308,17 +37736,23 @@
case "console":
return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
case "$":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
case "describe":
case "suite":
case "it":
case "test":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha;
case "process":
case "require":
case "Buffer":
case "module":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
case "Map":
case "Set":
case "Promise":
@@ -37440,9 +37874,8 @@
}
return false;
}
- function hasNarrowableDeclaredType(expr) {
- var type = getDeclaredTypeOfReference(expr);
- return !!(type && type.flags & 1048576);
+ function isSyntheticThisPropertyAccess(expr) {
+ return ts.isAccessExpression(expr) && expr.expression.kind === 100 && !!(expr.expression.flags & 8);
}
function findDiscriminantProperties(sourceProperties, target) {
var result;
@@ -37512,8 +37945,8 @@
}
function getTypeFactsOfTypes(types) {
var result = 0;
- for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
- var t = types_11[_i];
+ for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
+ var t = types_12[_i];
result |= getTypeFacts(t);
}
return result;
@@ -37786,7 +38219,7 @@
if (type.flags & 1048576) {
var types = type.types;
var filtered = ts.filter(types, f);
- return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly);
+ return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
}
return f(type) ? type : neverType;
}
@@ -37800,8 +38233,8 @@
var types = type.types;
var mappedType;
var mappedTypes;
- for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
- var current = types_12[_i];
+ for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
+ var current = types_13[_i];
var t = mapper(current);
if (t) {
if (!mappedType) {
@@ -37872,8 +38305,8 @@
}
function isEvolvingArrayTypeList(types) {
var hasEvolvingArrayType = false;
- for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
- var t = types_13[_i];
+ for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
+ var t = types_14[_i];
if (!(t.flags & 131072)) {
if (!(ts.getObjectFlags(t) & 256)) {
return false;
@@ -38297,6 +38730,15 @@
assumeTrue = !assumeTrue;
}
var valueType = getTypeOfExpression(value);
+ if ((type.flags & 2) && (operator === 35) && assumeTrue) {
+ if (valueType.flags & (131068 | 67108864)) {
+ return valueType;
+ }
+ if (valueType.flags & 524288) {
+ return nonPrimitiveType;
+ }
+ return type;
+ }
if (valueType.flags & 98304) {
if (!strictNullChecks) {
return type;
@@ -38325,7 +38767,7 @@
function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
var target = getReferenceCandidate(typeOfExpr.expression);
if (!isMatchingReference(reference, target)) {
- if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) {
+ if (containsMatchingReference(reference, target)) {
return declaredType;
}
return type;
@@ -38369,6 +38811,27 @@
}
var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
+ if ((type.flags & 2) && !hasDefaultClause) {
+ var groundClauseTypes = void 0;
+ for (var i = 0; i < clauseTypes.length; i += 1) {
+ var t = clauseTypes[i];
+ if (t.flags & (131068 | 67108864)) {
+ if (groundClauseTypes !== undefined) {
+ groundClauseTypes.push(t);
+ }
+ }
+ else if (t.flags & 524288) {
+ if (groundClauseTypes === undefined) {
+ groundClauseTypes = clauseTypes.slice(0, i);
+ }
+ groundClauseTypes.push(nonPrimitiveType);
+ }
+ else {
+ return type;
+ }
+ }
+ return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
+ }
var discriminantType = getUnionType(clauseTypes);
var caseType = discriminantType.flags & 131072 ? neverType :
replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
@@ -38434,7 +38897,7 @@
function narrowTypeByInstanceof(type, expr, assumeTrue) {
var left = getReferenceCandidate(expr.left);
if (!isMatchingReference(reference, left)) {
- if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) {
+ if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) {
return declaredType;
}
return type;
@@ -38490,7 +38953,7 @@
return type;
}
if (ts.isIdentifierTypePredicate(predicate)) {
- var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)];
+ var predicateArgument = callExpression.arguments[predicate.parameterIndex];
if (predicateArgument) {
if (isMatchingReference(reference, predicateArgument)) {
return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
@@ -38556,7 +39019,7 @@
return ts.findAncestor(node.parent, function (node) {
return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
node.kind === 245 ||
- node.kind === 279 ||
+ node.kind === 284 ||
node.kind === 154;
});
}
@@ -38657,7 +39120,7 @@
}
else if (declaration.kind === 209) {
var container = ts.getThisContainer(node, false);
- while (container.kind !== 279) {
+ while (container.kind !== 284) {
if (container.parent === declaration) {
if (container.kind === 154 && ts.hasModifier(container, 32)) {
getNodeLinks(declaration).flags |= 16777216;
@@ -38748,6 +39211,7 @@
function checkNestedBlockScopedBinding(node, symbol) {
if (languageVersion >= 2 ||
(symbol.flags & (2 | 32)) === 0 ||
+ ts.isSourceFile(symbol.valueDeclaration) ||
symbol.valueDeclaration.parent.kind === 274) {
return;
}
@@ -38893,21 +39357,26 @@
if (capturedByArrowFunction && languageVersion < 2) {
captureLexicalThis(node, container);
}
- var type = tryGetThisTypeAt(node, container);
- if (!type && noImplicitThis) {
- var diag = error(node, capturedByArrowFunction && container.kind === 279 ?
- 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);
+ var type = tryGetThisTypeAt(node, true, container);
+ if (noImplicitThis) {
+ var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
+ if (type === globalThisType_1 && capturedByArrowFunction) {
+ error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
+ }
+ else if (!type) {
+ var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
if (!ts.isSourceFile(container)) {
var outsideThis = tryGetThisTypeAt(container);
- if (outsideThis) {
- addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
+ if (outsideThis && outsideThis !== globalThisType_1) {
+ ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
+ }
}
}
}
return type || anyType;
}
- function tryGetThisTypeAt(node, container) {
+ function tryGetThisTypeAt(node, includeGlobalThis, container) {
+ if (includeGlobalThis === void 0) { includeGlobalThis = true; }
if (container === void 0) { container = ts.getThisContainer(node, false); }
var isInJS = ts.isInJSFile(node);
if (ts.isFunctionLike(container) &&
@@ -38946,6 +39415,15 @@
return getFlowTypeOfReference(node, type);
}
}
+ if (ts.isSourceFile(container)) {
+ if (container.commonJsModuleIndicator) {
+ var fileSymbol = getSymbolOfNode(container);
+ return fileSymbol && getTypeOfSymbol(fileSymbol);
+ }
+ else if (includeGlobalThis) {
+ return getTypeOfSymbol(globalThisSymbol);
+ }
+ }
}
function getClassNameFromPrototypeMethod(container) {
if (container.kind === 196 &&
@@ -38991,7 +39469,7 @@
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 289) {
+ if (jsdocType && jsdocType.kind === 294) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -39005,7 +39483,7 @@
}
}
function isInConstructorArgumentInitializer(node, constructorDecl) {
- return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151; });
+ return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 151 && n.parent === constructorDecl; });
}
function checkSuperExpression(node) {
var isCallExpression = node.parent.kind === 191 && node.parent.expression === node;
@@ -39149,7 +39627,7 @@
while (type) {
var thisType = getThisTypeFromContextualType(type);
if (thisType) {
- return instantiateType(thisType, getContextualMapper(containingLiteral));
+ return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
}
if (literal.parent.kind !== 275) {
break;
@@ -39414,7 +39892,15 @@
}
function getTypeOfPropertyOfContextualType(type, name) {
return mapType(type, function (t) {
- if (t.flags & 3670016) {
+ if (isGenericMappedType(t)) {
+ var constraint = getConstraintTypeFromMappedType(t);
+ var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
+ var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
+ if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
+ return substituteIndexedMappedType(t, propertyNameType);
+ }
+ }
+ else if (t.flags & 3670016) {
var prop = getPropertyOfType(t, name);
if (prop) {
return getTypeOfSymbol(prop);
@@ -39529,18 +40015,41 @@
return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 267 && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType);
}
function getApparentTypeOfContextualType(node) {
- var contextualType = getContextualType(node);
- contextualType = contextualType && mapType(contextualType, getApparentType);
- if (contextualType && contextualType.flags & 1048576) {
+ var contextualType = instantiateContextualType(getContextualType(node), node);
+ if (contextualType) {
+ var apparentType = mapType(contextualType, getApparentType, true);
+ if (apparentType.flags & 1048576) {
if (ts.isObjectLiteralExpression(node)) {
- return discriminateContextualTypeByObjectMembers(node, contextualType);
+ return discriminateContextualTypeByObjectMembers(node, apparentType);
}
else if (ts.isJsxAttributes(node)) {
- return discriminateContextualTypeByJSXAttributes(node, contextualType);
+ return discriminateContextualTypeByJSXAttributes(node, apparentType);
+ }
+ }
+ return apparentType;
+ }
+ }
+ function instantiateContextualType(contextualType, node) {
+ if (contextualType && maybeTypeOfKind(contextualType, 63176704)) {
+ var inferenceContext = getInferenceContext(node);
+ if (inferenceContext && inferenceContext.returnMapper) {
+ return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
}
}
return contextualType;
}
+ function instantiateInstantiableTypes(type, mapper) {
+ if (type.flags & 63176704) {
+ return instantiateType(type, mapper);
+ }
+ if (type.flags & 1048576) {
+ return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0);
+ }
+ if (type.flags & 2097152) {
+ return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
+ }
+ return type;
+ }
function getContextualType(node) {
if (node.flags & 8388608) {
return undefined;
@@ -39568,7 +40077,7 @@
return getContextualTypeForArgument(parent, node);
case 194:
case 212:
- return getTypeFromTypeNode(parent.type);
+ return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type);
case 204:
return getContextualTypeForBinaryOperand(node);
case 275:
@@ -39601,9 +40110,9 @@
}
return undefined;
}
- function getContextualMapper(node) {
- var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; });
- return ancestor ? ancestor.contextualMapper : identityMapper;
+ function getInferenceContext(node) {
+ var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
+ return ancestor && ancestor.inferenceContext;
}
function getContextualJsxElementAttributesType(node) {
if (ts.isJsxOpeningElement(node) && node.parent.contextualType) {
@@ -39761,8 +40270,8 @@
}
var signatureList;
var types = type.types;
- for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
- var current = types_14[_i];
+ for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
+ var current = types_15[_i];
var signature = getContextualCallSignature(current, node);
if (signature) {
if (!signatureList) {
@@ -39776,12 +40285,7 @@
}
}
}
- var result;
- if (signatureList) {
- result = cloneSignature(signatureList[0]);
- result.unionSignatures = signatureList;
- }
- return result;
+ return signatureList && createUnionSignature(signatureList[0], signatureList);
}
function checkSpreadExpression(node, checkMode) {
if (languageVersion < 2 && compilerOptions.downlevelIteration) {
@@ -39801,6 +40305,7 @@
var elementTypes = [];
var inDestructuringPattern = ts.isAssignmentTarget(node);
var contextualType = getApparentTypeOfContextualType(node);
+ var inConstContext = isConstContext(node);
for (var index = 0; index < elementCount; index++) {
var e = elements[index];
if (inDestructuringPattern && e.kind === 208) {
@@ -39829,20 +40334,23 @@
type.pattern = node;
return type;
}
- else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) {
+ else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, inConstContext)) {
return tupleResult;
}
else if (forceTuple) {
return createTupleType(elementTypes, minLength, hasRestElement);
}
}
- return getArrayLiteralType(elementTypes, 2);
+ return createArrayType(elementTypes.length ?
+ getUnionType(elementTypes, 2) :
+ strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext);
}
- function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) {
+ function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) {
if (elementCount === void 0) { elementCount = elementTypes.length; }
- if (contextualType && forEachType(contextualType, isTupleLikeType)) {
+ if (readonly === void 0) { readonly = false; }
+ if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) {
var minLength = elementCount - (hasRestElement ? 1 : 0);
- var pattern = contextualType.pattern;
+ var pattern = contextualType && contextualType.pattern;
if (!hasRestElement && pattern && (pattern.kind === 185 || pattern.kind === 187)) {
var patternElements = pattern.elements;
for (var i = elementCount; i < patternElements.length; i++) {
@@ -39858,14 +40366,8 @@
}
}
}
- return createTupleType(elementTypes, minLength, hasRestElement);
- }
+ return createTupleType(elementTypes, minLength, hasRestElement, readonly);
}
- function getArrayLiteralType(elementTypes, unionReduction) {
- if (unionReduction === void 0) { unionReduction = 1; }
- return createArrayType(elementTypes.length ?
- getUnionType(elementTypes, unionReduction) :
- strictNullChecks ? implicitNeverType : undefinedWideningType);
}
function isNumericName(name) {
switch (name.kind) {
@@ -39904,15 +40406,15 @@
}
return links.resolvedType;
}
- function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) {
+ function getObjectLiteralIndexInfo(node, offset, properties, kind) {
var propTypes = [];
for (var i = 0; i < properties.length; i++) {
- if (kind === 0 || isNumericName(propertyNodes[i + offset].name)) {
+ if (kind === 0 || isNumericName(node.properties[i + offset].name)) {
propTypes.push(getTypeOfSymbol(properties[i]));
}
}
var unionType = propTypes.length ? getUnionType(propTypes, 2) : undefinedType;
- return createIndexInfo(unionType, false);
+ return createIndexInfo(unionType, isConstContext(node));
}
function getImmediateAliasedSymbol(symbol) {
ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here.");
@@ -39931,14 +40433,15 @@
var propertiesTable;
var propertiesArray = [];
var spread = emptyObjectType;
- var propagatedFlags = 0;
var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === 184 || contextualType.pattern.kind === 188);
+ var inConstContext = isConstContext(node);
+ var checkFlags = inConstContext ? 8 : 0;
var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
var enumTag = ts.getJSDocEnumTag(node);
var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
- var typeFlags = 0;
+ var objectFlags = freshObjectLiteralFlag;
var patternWithComputedProperties = false;
var hasComputedStringProperty = false;
var hasComputedNumberProperty = false;
@@ -39965,11 +40468,11 @@
checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
}
}
- typeFlags |= type.flags;
+ objectFlags |= ts.getObjectFlags(type) & 917504;
var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
var prop = nameType ?
- createSymbol(4 | member.flags, getPropertyNameFromType(nameType), 2048) :
- createSymbol(4 | member.flags, member.escapedName);
+ createSymbol(4 | member.flags, getPropertyNameFromType(nameType), checkFlags | 2048) :
+ createSymbol(4 | member.flags, member.escapedName, checkFlags);
if (nameType) {
prop.nameType = nameType;
}
@@ -40003,19 +40506,18 @@
checkExternalEmitHelpers(memberDecl, 2);
}
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768);
+ spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
propertiesArray = [];
propertiesTable = ts.createSymbolTable();
hasComputedStringProperty = false;
hasComputedNumberProperty = false;
- typeFlags = 0;
}
var type = checkExpression(memberDecl.expression);
if (!isValidSpreadType(type)) {
error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
return errorType;
}
- spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768);
+ spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
offset = i + 1;
continue;
}
@@ -40055,17 +40557,16 @@
}
if (spread !== emptyObjectType) {
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768);
+ spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
}
return spread;
}
return createObjectLiteralType();
function createObjectLiteralType() {
- var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined;
- var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined;
+ var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0) : undefined;
+ var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1) : undefined;
var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
- result.flags |= 268435456 | typeFlags & 939524096;
- result.objectFlags |= 128 | freshObjectLiteralFlag;
+ result.objectFlags |= objectFlags | 128 | 262144;
if (isJSObjectLiteral) {
result.objectFlags |= 16384;
}
@@ -40075,7 +40576,6 @@
if (inDestructuringPattern) {
result.pattern = node;
}
- propagatedFlags |= result.flags & 939524096;
return result;
}
}
@@ -40133,7 +40633,6 @@
var hasSpreadAnyType = false;
var typeToIntersect;
var explicitlySpecifyChildrenAttribute = false;
- var typeFlags = 0;
var objectFlags = 4096;
var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
@@ -40141,7 +40640,7 @@
var member = attributeDecl.symbol;
if (ts.isJsxAttribute(attributeDecl)) {
var exprType = checkJsxAttribute(attributeDecl, checkMode);
- typeFlags |= exprType.flags & 939524096;
+ objectFlags |= ts.getObjectFlags(exprType) & 917504;
var attributeSymbol = createSymbol(4 | 33554432 | member.flags, member.escapedName);
attributeSymbol.declarations = member.declarations;
attributeSymbol.parent = member.parent;
@@ -40158,7 +40657,7 @@
else {
ts.Debug.assert(attributeDecl.kind === 269);
if (attributesTable.size > 0) {
- spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, false);
attributesTable = ts.createSymbolTable();
}
var exprType = checkExpressionCached(attributeDecl.expression, checkMode);
@@ -40166,7 +40665,7 @@
hasSpreadAnyType = true;
}
if (isValidSpreadType(exprType)) {
- spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, false);
}
else {
typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
@@ -40175,7 +40674,7 @@
}
if (!hasSpreadAnyType) {
if (attributesTable.size > 0) {
- spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, false);
}
}
var parent = openingLikeElement.parent.kind === 260 ? openingLikeElement.parent : undefined;
@@ -40196,7 +40695,7 @@
childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
var childPropMap = ts.createSymbolTable();
childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
- spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, undefined, undefined), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, undefined, undefined), attributes.symbol, objectFlags, false);
}
}
if (hasSpreadAnyType) {
@@ -40209,8 +40708,7 @@
function createJsxAttributesType() {
objectFlags |= freshObjectLiteralFlag;
var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined);
- result.flags |= 268435456 | typeFlags;
- result.objectFlags |= 128 | objectFlags;
+ result.objectFlags |= objectFlags | 128 | 262144;
return result;
}
}
@@ -40219,7 +40717,7 @@
for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
var child = _a[_i];
if (child.kind === 11) {
- if (!child.containsOnlyWhiteSpaces) {
+ if (!child.containsOnlyTriviaWhiteSpaces) {
childrenTypes.push(stringType);
}
}
@@ -40276,7 +40774,7 @@
var namespaceName = getJsxNamespace(location);
var resolvedNamespace = resolveName(location, namespaceName, 1920, undefined, namespaceName, false);
if (resolvedNamespace) {
- var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920);
+ var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920));
if (candidate) {
if (links) {
links.jsxNamespace = candidate;
@@ -40624,6 +41122,15 @@
if (isJSLiteralType(leftType)) {
return anyType;
}
+ if (leftType.symbol === globalThisSymbol) {
+ if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418)) {
+ error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
+ }
+ else if (noImplicitAny) {
+ error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
+ }
+ return anyType;
+ }
if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
reportNonexistentProperty(right, leftType.flags & 262144 && leftType.isThisType ? apparentType : leftType);
}
@@ -40694,7 +41201,7 @@
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));
+ ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
}
}
function isInPropertyInitializer(node) {
@@ -40703,6 +41210,19 @@
case 154:
return true;
case 275:
+ case 156:
+ case 158:
+ case 159:
+ case 277:
+ case 149:
+ case 216:
+ case 270:
+ case 267:
+ case 268:
+ case 269:
+ case 262:
+ case 211:
+ case 273:
return false;
default:
return ts.isExpressionNode(node) ? false : "quit";
@@ -40766,7 +41286,7 @@
}
var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
if (relatedInfo) {
- addRelatedInfo(resultDiagnostic, relatedInfo);
+ ts.addRelatedInfo(resultDiagnostic, relatedInfo);
}
diagnostics.add(resultDiagnostic);
}
@@ -41098,43 +41618,43 @@
}
return undefined;
}
- function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) {
+ function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
var context = createInferenceContext(signature.typeParameters, signature, 0, compareTypes);
- var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature;
- forEachMatchingParameterType(sourceSignature, signature, function (source, target) {
+ var restType = getEffectiveRestType(contextualSignature);
+ var mapper = inferenceContext && (restType && restType.flags & 262144 ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
+ var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
+ applyToParameterTypes(sourceSignature, signature, function (source, target) {
inferTypes(context.inferences, source, target);
});
- if (!contextualMapper) {
- inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8);
+ if (!inferenceContext) {
+ applyToReturnTypes(contextualSignature, signature, function (source, target) {
+ inferTypes(context.inferences, source, target, 8);
+ });
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
}
- function inferJsxTypeArguments(node, signature, excludeArgument, context) {
+ function inferJsxTypeArguments(node, signature, checkMode, context) {
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context);
+ var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
inferTypes(context.inferences, checkAttrType, paramType);
return getInferredTypes(context);
}
- function inferTypeArguments(node, signature, args, excludeArgument, context) {
- for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) {
- var inference = _a[_i];
- if (!inference.isFixed) {
- inference.inferredType = undefined;
- }
- }
+ function inferTypeArguments(node, signature, args, checkMode, context) {
if (ts.isJsxOpeningLikeElement(node)) {
- return inferJsxTypeArguments(node, signature, excludeArgument, context);
+ return inferJsxTypeArguments(node, signature, checkMode, context);
}
if (node.kind !== 152) {
var contextualType = getContextualType(node);
if (contextualType) {
- var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node)));
+ var outerMapper = getMapperFromContext(cloneInferenceContext(getInferenceContext(node), 1));
+ var instantiatedType = instantiateType(contextualType, outerMapper);
var contextualSignature = getSingleCallSignature(instantiatedType);
var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ?
getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) :
instantiatedType;
var inferenceTargetType = getReturnTypeOfSignature(signature);
inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8);
+ context.returnMapper = getMapperFromContext(cloneInferredPartOfContext(context));
}
}
var thisType = getThisTypeOfSignature(signature);
@@ -41149,8 +41669,7 @@
var arg = args[i];
if (arg.kind !== 210) {
var paramType = getTypeAtPosition(signature, i);
- var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
- var argType = checkExpressionWithContextualType(arg, paramType, mapper);
+ var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
inferTypes(context.inferences, argType, paramType);
}
}
@@ -41172,7 +41691,7 @@
if (isSpreadArgument(arg)) {
return arg.kind === 215 ?
createArrayType(arg.type) :
- getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context));
+ getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0));
}
}
var contextualType = getIndexTypeOfType(restType, 1) || anyType;
@@ -41180,7 +41699,7 @@
var types = [];
var spreadIndex = -1;
for (var i = index; i < argCount; i++) {
- var argType = checkExpressionWithContextualType(args[i], contextualType, context);
+ var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0);
if (spreadIndex < 0 && isSpreadArgument(args[i])) {
spreadIndex = i - index;
}
@@ -41225,14 +41744,14 @@
}
return 2;
}
- function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors) {
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined);
+ var attributesType = checkExpressionWithContextualType(node.attributes, paramType, undefined, checkMode);
return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes);
}
- function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignature(node, args, signature, relation, checkMode, reportErrors) {
if (ts.isJsxOpeningLikeElement(node)) {
- return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors);
+ return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors);
}
var thisType = getThisTypeOfSignature(signature);
if (thisType && thisType !== voidType && node.kind !== 192) {
@@ -41251,8 +41770,8 @@
var arg = args[i];
if (arg.kind !== 210) {
var paramType = getTypeAtPosition(signature, i);
- var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
- var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType;
+ var argType = checkExpressionWithContextualType(arg, paramType, undefined, checkMode);
+ var checkArgType = checkMode & 4 ? getRegularTypeOfObjectLiteral(argType) : argType;
if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
return false;
}
@@ -41386,25 +41905,41 @@
if (argCount <= max && hasSpreadArgument) {
argCount--;
}
+ var spanArray;
var related;
+ var error = hasRestParameter || hasSpreadArgument ? 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 : ts.Diagnostics.Expected_0_arguments_but_got_1;
if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
if (paramDecl) {
related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined);
}
}
- 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;
- var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount);
- return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1;
- }
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);
}
- var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount);
- return related ? addRelatedInfo(diagnostic, related) : diagnostic;
+ if (!hasSpreadArgument && argCount < min) {
+ var diagnostic_1 = ts.createDiagnosticForNode(node, error, paramRange, argCount);
+ return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
+ }
+ if (hasRestParameter || hasSpreadArgument) {
+ spanArray = ts.createNodeArray(args);
+ if (hasSpreadArgument && argCount) {
+ var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
+ spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
+ }
+ }
+ else {
+ spanArray = ts.createNodeArray(args.slice(max));
+ }
+ spanArray.pos = ts.first(spanArray).pos;
+ spanArray.end = ts.last(spanArray).end;
+ if (spanArray.end === spanArray.pos) {
+ spanArray.end++;
+ }
+ var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
+ return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
}
function getTypeArgumentArityError(node, signatures, typeArguments) {
var argCount = typeArguments.length;
@@ -41432,7 +41967,7 @@
}
return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
}
- function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) {
+ function resolveCall(node, signatures, candidatesOutArray, checkMode, fallbackError) {
var isTaggedTemplate = node.kind === 193;
var isDecorator = node.kind === 152;
var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
@@ -41454,12 +41989,12 @@
}
var args = getEffectiveCallArguments(node);
var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
- var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined;
+ var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 : 0;
var candidateForArgumentError;
var candidateForArgumentArityError;
var candidateForTypeArgumentError;
var result;
- var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 && node.arguments.hasTrailingComma;
+ var signatureHelpTrailingComma = !!(checkMode & 16) && node.kind === 191 && node.arguments.hasTrailingComma;
if (candidates.length > 1) {
result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma);
}
@@ -41471,7 +42006,7 @@
}
if (reportErrors) {
if (candidateForArgumentError) {
- checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true);
+ checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, 0, true);
}
else if (candidateForArgumentArityError) {
diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
@@ -41503,7 +42038,7 @@
if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
return undefined;
}
- if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) {
+ if (!checkApplicableSignature(node, args, candidate, relation, 0, false)) {
candidateForArgumentError = candidate;
return undefined;
}
@@ -41527,9 +42062,10 @@
}
else {
inferenceContext = createInferenceContext(candidate.typeParameters, candidate, ts.isInJSFile(node) ? 2 : 0);
- typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
+ typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8, inferenceContext);
+ argCheckMode |= inferenceContext.flags & 4 ? 8 : 0;
}
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
candidateForArgumentArityError = checkCandidate;
continue;
@@ -41538,23 +42074,23 @@
else {
checkCandidate = candidate;
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, false)) {
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
}
continue;
}
- if (excludeArgument) {
- excludeArgument = undefined;
+ if (argCheckMode) {
+ argCheckMode = 0;
if (inferenceContext) {
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
candidateForArgumentArityError = checkCandidate;
continue;
}
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, false)) {
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
}
@@ -41567,18 +42103,6 @@
return undefined;
}
}
- function getExcludeArgument(args) {
- var excludeArgument;
- for (var i = 0; i < args.length; i++) {
- if (isContextSensitive(args[i])) {
- if (!excludeArgument) {
- excludeArgument = new Array(args.length);
- }
- excludeArgument[i] = true;
- }
- }
- return excludeArgument;
- }
function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
ts.Debug.assert(candidates.length > 0);
return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
@@ -41650,7 +42174,7 @@
}
function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
var inferenceContext = createInferenceContext(typeParameters, candidate, ts.isInJSFile(node) ? 2 : 0);
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext);
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 | 8, inferenceContext);
return createSignatureInstantiation(candidate, typeArgumentTypes);
}
function getLongestCandidateIndex(candidates, argsCount) {
@@ -41669,7 +42193,7 @@
}
return maxParamsIndex;
}
- function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveCallExpression(node, candidatesOutArray, checkMode) {
if (node.expression.kind === 98) {
var superType = checkSuperExpression(node.expression);
if (isTypeAny(superType)) {
@@ -41683,7 +42207,7 @@
var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
if (baseTypeNode) {
var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
- return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, baseConstructors, candidatesOutArray, checkMode);
}
}
return resolveUntypedCall(node);
@@ -41720,17 +42244,24 @@
}
return resolveErrorCall(node);
}
+ if (checkMode & 8 && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
+ skippedGenericFunction(node, checkMode);
+ return resolvingSignature;
+ }
if (callSignatures.some(function (sig) { return ts.isInJSFile(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);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
+ }
+ function isGenericFunctionReturningFunction(signature) {
+ return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
}
function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144) ||
!numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 | 131072)) && isTypeAssignableTo(funcType, globalFunctionType);
}
- function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveNewExpression(node, candidatesOutArray, checkMode) {
if (node.arguments && languageVersion < 1) {
var spreadIndex = getSpreadArgumentIndex(node.arguments);
if (spreadIndex >= 0) {
@@ -41761,11 +42292,11 @@
error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
return resolveErrorCall(node);
}
- return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, constructSignatures, candidatesOutArray, checkMode);
}
var callSignatures = getSignaturesOfType(expressionType, 0);
if (callSignatures.length) {
- var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode);
if (!noImplicitAny) {
if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
@@ -41787,12 +42318,11 @@
var firstBase = baseTypes[0];
if (firstBase.flags & 2097152) {
var types = firstBase.types;
- var mixinCount = ts.countWhere(types, isMixinConstructorType);
+ var mixinFlags = findMixins(types);
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 (!mixinFlags[i]) {
if (ts.getObjectFlags(intersectionMember) & (1 | 2)) {
if (intersectionMember.symbol === target) {
return true;
@@ -41802,6 +42332,7 @@
}
}
}
+ i++;
}
return false;
}
@@ -41843,7 +42374,7 @@
var diagnostic = error(node, (kind === 0 ?
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, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
+ invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
}
function invocationErrorRecovery(apparentType, kind, diagnostic) {
if (!apparentType.symbol) {
@@ -41854,10 +42385,10 @@
var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
if (!sigs || !sigs.length)
return;
- 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));
+ 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, isForSignatureHelp) {
+ function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
var tagType = checkExpression(node.tag);
var apparentType = getApparentType(tagType);
if (apparentType === errorType) {
@@ -41872,7 +42403,7 @@
invocationError(node, apparentType, 0);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
}
function getDiagnosticHeadMessageForDecoratorResolution(node) {
switch (node.parent.kind) {
@@ -41891,7 +42422,7 @@
return ts.Debug.fail();
}
}
- function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveDecorator(node, candidatesOutArray, checkMode) {
var funcType = checkExpression(node.expression);
var apparentType = getApparentType(funcType);
if (apparentType === errorType) {
@@ -41916,7 +42447,7 @@
invocationErrorRecovery(apparentType, 0, diag);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode, headMessage);
}
function createSignatureForJSXIntrinsic(node, result) {
var namespace = getJsxNamespaceAt(node);
@@ -41928,11 +42459,11 @@
parameterSymbol.type = result;
return createSignature(declaration, undefined, undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, undefined, 1, false, false);
}
- function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
var fakeSignature = createSignatureForJSXIntrinsic(node, result);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), undefined), result, node.tagName, node.attributes);
+ checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), undefined, 0), result, node.tagName, node.attributes);
return fakeSignature;
}
var exprTypes = checkExpression(node.tagName);
@@ -41948,7 +42479,7 @@
error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
return resolveErrorCall(node);
}
- return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, signatures, candidatesOutArray, checkMode);
}
function isPotentiallyUncalledDecorator(decorator, signatures) {
return signatures.length && ts.every(signatures, function (signature) {
@@ -41957,32 +42488,33 @@
signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
});
}
- function resolveSignature(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveSignature(node, candidatesOutArray, checkMode) {
switch (node.kind) {
case 191:
- return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveCallExpression(node, candidatesOutArray, checkMode);
case 192:
- return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveNewExpression(node, candidatesOutArray, checkMode);
case 193:
- return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
case 152:
- return resolveDecorator(node, candidatesOutArray, isForSignatureHelp);
+ return resolveDecorator(node, candidatesOutArray, checkMode);
case 262:
case 261:
- return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp);
+ return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
}
throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
}
- function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) {
- if (isForSignatureHelp === void 0) { isForSignatureHelp = false; }
+ function getResolvedSignature(node, candidatesOutArray, checkMode) {
var links = getNodeLinks(node);
var cached = links.resolvedSignature;
if (cached && cached !== resolvingSignature && !candidatesOutArray) {
return cached;
}
links.resolvedSignature = resolvingSignature;
- var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp);
+ var result = resolveSignature(node, candidatesOutArray, checkMode || 0);
+ if (result !== resolvingSignature) {
links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ }
return result;
}
function isJSConstructor(node) {
@@ -42047,10 +42579,13 @@
}
return links.inferredClassType;
}
- function checkCallExpression(node) {
+ function checkCallExpression(node, checkMode) {
if (!checkGrammarTypeArguments(node, node.typeArguments))
checkGrammarArguments(node.arguments);
- var signature = getResolvedSignature(node);
+ var signature = getResolvedSignature(node, undefined, checkMode);
+ if (signature === resolvingSignature) {
+ return nonInferrableType;
+ }
if (node.expression.kind === 98) {
return voidType;
}
@@ -42142,7 +42677,7 @@
var anonymousSymbol = createSymbol(2048, "__type");
var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, undefined, undefined);
anonymousSymbol.type = defaultContainingObject;
- synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, 0, 0) : defaultContainingObject;
+ synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, 0, false) : defaultContainingObject;
}
else {
synthType.syntheticType = type;
@@ -42186,9 +42721,37 @@
function checkAssertion(node) {
return checkAssertionWorker(node, node.type, node.expression);
}
+ function isValidConstAssertionArgument(node) {
+ switch (node.kind) {
+ case 10:
+ case 14:
+ case 8:
+ case 9:
+ case 102:
+ case 87:
+ case 187:
+ case 188:
+ return true;
+ case 195:
+ return isValidConstAssertionArgument(node.expression);
+ case 202:
+ var op = node.operator;
+ var arg = node.operand;
+ return op === 39 && (arg.kind === 8 || arg.kind === 9) ||
+ op === 38 && arg.kind === 8;
+ }
+ return false;
+ }
function checkAssertionWorker(errNode, type, expression, checkMode) {
- var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode)));
+ var exprType = checkExpression(expression, checkMode);
+ if (ts.isConstTypeReference(type)) {
+ if (!isValidConstAssertionArgument(expression)) {
+ error(expression, ts.Diagnostics.A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal);
+ }
+ return getRegularTypeOfLiteralType(exprType);
+ }
checkSourceElement(type);
+ exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
var targetType = getTypeFromTypeNode(type);
if (produceDiagnostics && targetType !== errorType) {
var widenedType = getWidenedType(exprType);
@@ -42227,7 +42790,7 @@
}
}
function checkImportMetaProperty(node) {
- if (languageVersion < 6 || moduleKind < ts.ModuleKind.ESNext) {
+ if (languageVersion < 7 || moduleKind < ts.ModuleKind.ESNext) {
error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options);
}
var file = ts.getSourceFileOfNode(node);
@@ -42255,7 +42818,7 @@
if (isTupleType(restType)) {
var associatedNames = restType.target.associatedNames;
var index = pos - paramCount;
- return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index;
+ return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
}
return restParameter.escapedName;
}
@@ -42269,32 +42832,33 @@
}
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);
+ var index = pos - paramCount;
+ if (!isTupleType(restType) || restType.target.hasRestElement || index < (restType.typeArguments || ts.emptyArray).length) {
+ return getIndexedAccessType(restType, getLiteralType(index));
}
- return getIndexTypeOfType(restType, 1);
}
return undefined;
}
function getRestTypeAtPosition(source, pos) {
var paramCount = getParameterCount(source);
var restType = getEffectiveRestType(source);
- if (restType && pos === paramCount - 1) {
+ var nonRestCount = paramCount - (restType ? 1 : 0);
+ if (restType && pos === nonRestCount) {
return restType;
}
- var start = restType ? Math.min(pos, paramCount - 1) : pos;
var types = [];
var names = [];
- for (var i = start; i < paramCount; i++) {
+ for (var i = pos; i < nonRestCount; i++) {
types.push(getTypeAtPosition(source, i));
names.push(getParameterNameAtPosition(source, i));
}
+ if (restType) {
+ types.push(getIndexedAccessType(restType, numberType));
+ names.push(getParameterNameAtPosition(source, nonRestCount));
+ }
var minArgumentCount = getMinArgumentCount(source);
- var minLength = minArgumentCount < start ? 0 : minArgumentCount - start;
- return createTupleType(types, minLength, !!restType, names);
+ var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos;
+ return createTupleType(types, minLength, !!restType, false, names);
}
function getParameterCount(signature) {
var length = signature.parameters.length;
@@ -42342,17 +42906,24 @@
function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
}
- function inferFromAnnotatedParameters(signature, context, mapper) {
+ function inferFromAnnotatedParameters(signature, context, inferenceContext) {
var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
for (var i = 0; i < len; i++) {
var declaration = signature.parameters[i].valueDeclaration;
if (declaration.type) {
var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
if (typeNode) {
- inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
+ inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
}
}
}
+ var restType = getEffectiveRestType(context);
+ if (restType && restType.flags & 262144) {
+ var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
+ assignContextualParameterTypes(signature, instantiatedContext);
+ var restPos = getParameterCount(context) - 1;
+ inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
+ }
}
function assignContextualParameterTypes(signature, context) {
signature.typeParameters = context.typeParameters;
@@ -42445,7 +43016,7 @@
var functionFlags = ts.getFunctionFlags(func);
var type;
if (func.body.kind !== 218) {
- type = checkExpressionCached(func.body, checkMode);
+ type = checkExpressionCached(func.body, checkMode && checkMode & ~8);
if (functionFlags & 2) {
type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
}
@@ -42590,7 +43161,7 @@
ts.forEachReturnStatement(func.body, function (returnStatement) {
var expr = returnStatement.expression;
if (expr) {
- var type = checkExpressionCached(expr, checkMode);
+ var type = checkExpressionCached(expr, checkMode && checkMode & ~8);
if (functionFlags & 2) {
type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
}
@@ -42659,7 +43230,7 @@
function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
ts.Debug.assert(node.kind !== 156 || ts.isObjectLiteralMethod(node));
checkNodeDeferred(node);
- if (checkMode === 1 && isContextSensitive(node)) {
+ if (checkMode && checkMode & 4 && isContextSensitive(node)) {
if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) {
var links_1 = getNodeLinks(node);
if (links_1.contextFreeType) {
@@ -42668,7 +43239,7 @@
var returnType = getReturnTypeFromBody(node, checkMode);
var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, false, false);
var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
- returnOnlyType.flags |= 536870912;
+ returnOnlyType.objectFlags |= 524288;
return links_1.contextFreeType = returnOnlyType;
}
return anyFunctionType;
@@ -42689,12 +43260,12 @@
if (contextualSignature) {
var signature = getSignaturesOfType(type, 0)[0];
if (isContextSensitive(node)) {
- var contextualMapper = getContextualMapper(node);
- if (checkMode === 2) {
- inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper);
+ var inferenceContext = getInferenceContext(node);
+ if (checkMode && checkMode & 2) {
+ inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
}
- var instantiatedContextualSignature = contextualMapper === identityMapper ?
- contextualSignature : instantiateSignature(contextualSignature, contextualMapper);
+ var instantiatedContextualSignature = inferenceContext ?
+ instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
assignContextualParameterTypes(signature, instantiatedContextualSignature);
}
if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
@@ -42927,13 +43498,13 @@
return numberType;
}
function maybeTypeOfKind(type, kind) {
- if (type.flags & kind & ~134217728 || kind & 134217728 && isGenericMappedType(type)) {
+ if (type.flags & kind & ~131072 || kind & 131072 && isGenericMappedType(type)) {
return true;
}
if (type.flags & 3145728) {
var types = type.types;
- for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
- var t = types_15[_i];
+ for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
+ var t = types_16[_i];
if (maybeTypeOfKind(t, kind)) {
return true;
}
@@ -43002,8 +43573,8 @@
if (strictNullChecks && properties.length === 0) {
return checkNonNullType(sourceType, node);
}
- for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) {
- var p = properties_6[_i];
+ for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
+ var p = properties_5[_i];
checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis);
}
return sourceType;
@@ -43026,7 +43597,7 @@
return checkDestructuringAssignment(property.kind === 276 ? property : property.initializer, type);
}
else if (property.kind === 277) {
- if (languageVersion < 6) {
+ if (languageVersion < 7) {
checkExternalEmitHelpers(property, 4);
}
var nonRestNames = [];
@@ -43477,7 +44048,7 @@
}
if (node.asteriskToken) {
if ((functionFlags & 3) === 3 &&
- languageVersion < 6) {
+ languageVersion < 7) {
checkExternalEmitHelpers(node, 26624);
}
if ((functionFlags & 3) === 1 &&
@@ -43514,23 +44085,23 @@
}
return node;
}
- function checkExpressionWithContextualType(node, contextualType, contextualMapper) {
+ function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
var context = getContextNode(node);
var saveContextualType = context.contextualType;
- var saveContextualMapper = context.contextualMapper;
+ var saveInferenceContext = context.inferenceContext;
context.contextualType = contextualType;
- context.contextualMapper = contextualMapper;
- var checkMode = contextualMapper === identityMapper ? 1 :
- contextualMapper ? 2 : 3;
- var result = checkExpression(node, checkMode);
+ context.inferenceContext = inferenceContext;
+ var type = checkExpression(node, checkMode | 1 | (inferenceContext ? 2 : 0));
+ var result = maybeTypeOfKind(type, 2944) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
+ getRegularTypeOfLiteralType(type) : type;
context.contextualType = saveContextualType;
- context.contextualMapper = saveContextualMapper;
+ context.inferenceContext = saveInferenceContext;
return result;
}
function checkExpressionCached(node, checkMode) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- if (checkMode) {
+ if (checkMode && checkMode !== 0) {
return checkExpression(node, checkMode);
}
var saveFlowLoopStart = flowLoopStart;
@@ -43585,13 +44156,17 @@
}
return false;
}
- function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
- if (arguments.length === 2) {
- contextualType = getContextualType(node);
+ function isConstContext(node) {
+ var parent = node.parent;
+ return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
+ (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
+ (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
}
+ function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
var type = checkExpression(node, checkMode, forceTuple);
- return isTypeAssertion(node) ? type :
- getWidenedLiteralLikeTypeForContextualType(type, contextualType);
+ return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
+ isTypeAssertion(node) ? type :
+ getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
}
function checkPropertyAssignment(node, checkMode) {
if (node.name.kind === 149) {
@@ -43608,20 +44183,112 @@
return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
}
function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
- if (checkMode === 2) {
+ if (checkMode && checkMode & (2 | 8)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
+ if (checkMode & 8) {
+ skippedGenericFunction(node, checkMode);
+ return anyFunctionType;
+ }
var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType));
if (contextualSignature && !contextualSignature.typeParameters) {
- return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node)));
+ var context = getInferenceContext(node);
+ var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature));
+ if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
+ var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
+ var inferences_2 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
+ applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
+ inferTypes(inferences_2, source, target, 0, true);
+ });
+ if (ts.some(inferences_2, hasInferenceCandidates)) {
+ applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
+ inferTypes(inferences_2, source, target);
+ });
+ if (!hasOverlappingInferences(context.inferences, inferences_2)) {
+ mergeInferences(context.inferences, inferences_2);
+ context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
+ return getOrCreateTypeFromSignature(instantiatedSignature);
+ }
+ }
+ }
+ return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
}
}
}
}
return type;
}
+ function skippedGenericFunction(node, checkMode) {
+ if (checkMode & 2) {
+ var context = getInferenceContext(node);
+ context.flags |= 4;
+ }
+ }
+ function hasInferenceCandidates(info) {
+ return !!(info.candidates || info.contraCandidates);
+ }
+ function hasOverlappingInferences(a, b) {
+ for (var i = 0; i < a.length; i++) {
+ if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ function mergeInferences(target, source) {
+ for (var i = 0; i < target.length; i++) {
+ if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
+ target[i] = source[i];
+ }
+ }
+ }
+ function getUniqueTypeParameters(context, typeParameters) {
+ var result = [];
+ var oldTypeParameters;
+ var newTypeParameters;
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var tp = typeParameters_2[_i];
+ var name = tp.symbol.escapedName;
+ if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
+ var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
+ var symbol = createSymbol(262144, newName);
+ var newTypeParameter = createTypeParameter(symbol);
+ newTypeParameter.target = tp;
+ oldTypeParameters = ts.append(oldTypeParameters, tp);
+ newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
+ result.push(newTypeParameter);
+ }
+ else {
+ result.push(tp);
+ }
+ }
+ if (newTypeParameters) {
+ var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
+ for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
+ var tp = newTypeParameters_1[_a];
+ tp.mapper = mapper;
+ }
+ }
+ return result;
+ }
+ function hasTypeParameterByName(typeParameters, name) {
+ return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
+ }
+ function getUniqueTypeParameterName(typeParameters, baseName) {
+ var len = baseName.length;
+ while (len > 1 && baseName.charCodeAt(len - 1) >= 48 && baseName.charCodeAt(len - 1) <= 57)
+ len--;
+ var s = baseName.slice(0, len);
+ for (var index = 1; true; index++) {
+ var augmentedName = (s + index);
+ if (!hasTypeParameterByName(typeParameters, augmentedName)) {
+ return augmentedName;
+ }
+ }
+ }
function getTypeOfExpression(node, cache) {
var expr = ts.skipParentheses(node);
if (expr.kind === 191 && expr.expression.kind !== 98 && !ts.isRequireCall(expr, true) && !isSymbolOrSymbolForCall(expr)) {
@@ -43631,7 +44298,7 @@
return getReturnTypeOfSignature(signature);
}
}
- else if (expr.kind === 194 || expr.kind === 212) {
+ else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
return getTypeFromTypeNode(expr.type);
}
return cache ? checkExpressionCached(node) : checkExpression(node);
@@ -43643,20 +44310,22 @@
}
var saveContextualType = node.contextualType;
node.contextualType = anyType;
- var type = links.contextFreeType = checkExpression(node, 1);
+ var type = links.contextFreeType = checkExpression(node, 4);
node.contextualType = saveContextualType;
return type;
}
function checkExpression(node, checkMode, forceTuple) {
- var type;
- if (node.kind === 148) {
- type = checkQualifiedName(node);
- }
- else {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
- type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
- }
+ var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
if (isConstEnumObjectType(type)) {
+ checkConstEnumAccess(node, type);
+ }
+ currentNode = saveCurrentNode;
+ return type;
+ }
+ function checkConstEnumAccess(node, type) {
var ok = (node.parent.kind === 189 && node.parent.expression === node) ||
(node.parent.kind === 190 && node.parent.expression === node) ||
((node.kind === 72 || node.kind === 148) && isInRightSideOfImportOrExportAssignment(node) ||
@@ -43664,8 +44333,13 @@
if (!ok) {
error(node, ts.Diagnostics.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);
}
+ if (compilerOptions.isolatedModules) {
+ ts.Debug.assert(!!(type.symbol.flags & 128));
+ var constEnumDeclaration = type.symbol.valueDeclaration;
+ if (constEnumDeclaration.flags & 4194304) {
+ error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
+ }
}
- return type;
}
function checkParenthesizedExpression(node, checkMode) {
var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
@@ -43707,6 +44381,8 @@
return checkObjectLiteral(node, checkMode);
case 189:
return checkPropertyAccessExpression(node);
+ case 148:
+ return checkQualifiedName(node);
case 190:
return checkIndexedAccess(node);
case 191:
@@ -43714,7 +44390,7 @@
return checkImportCallExpression(node);
}
case 192:
- return checkCallExpression(node);
+ return checkCallExpression(node, checkMode);
case 193:
return checkTaggedTemplateExpression(node);
case 195:
@@ -43777,9 +44453,7 @@
checkSourceElement(node.constraint);
checkSourceElement(node.default);
var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
- if (!hasNonCircularBaseConstraint(typeParameter)) {
- error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter));
- }
+ getBaseConstraintOfType(typeParameter);
if (!hasNonCircularTypeParameterDefault(typeParameter)) {
error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
}
@@ -43815,7 +44489,7 @@
error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
}
}
- if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) {
+ if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) {
error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
}
}
@@ -43825,7 +44499,8 @@
error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
return;
}
- var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent));
+ var signature = getSignatureFromDeclaration(parent);
+ var typePredicate = getTypePredicateOfSignature(signature);
if (!typePredicate) {
return;
}
@@ -43836,12 +44511,12 @@
}
else {
if (typePredicate.parameterIndex >= 0) {
- if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) {
+ if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) {
error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
}
else {
var leadingError = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
- checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError);
+ checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError);
}
}
else if (parameterName) {
@@ -43904,7 +44579,7 @@
}
var functionFlags = ts.getFunctionFlags(node);
if (!(functionFlags & 4)) {
- if ((functionFlags & 3) === 3 && languageVersion < 6) {
+ if ((functionFlags & 3) === 3 && languageVersion < 7) {
checkExternalEmitHelpers(node, 6144);
}
if ((functionFlags & 3) === 2 && languageVersion < 4) {
@@ -43951,7 +44626,7 @@
checkAsyncFunctionReturnType(node, returnTypeNode);
}
}
- if (node.kind !== 162 && node.kind !== 289) {
+ if (node.kind !== 162 && node.kind !== 294) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -44549,7 +45224,7 @@
for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) {
var signature = signatures_6[_a];
if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
- error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation);
+ ts.addRelatedInfo(error(signature.declaration, ts.Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), ts.createDiagnosticForNode(bodyDeclaration, ts.Diagnostics.The_implementation_signature_is_declared_here));
break;
}
}
@@ -44610,8 +45285,8 @@
switch (d.kind) {
case 241:
case 242:
- case 304:
- case 297:
+ case 309:
+ case 302:
return 2;
case 244:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0
@@ -44620,7 +45295,7 @@
case 240:
case 243:
return 2 | 1;
- case 279:
+ case 284:
return 2 | 1 | 4;
case 254:
if (!ts.isEntityNameExpression(d.expression)) {
@@ -44856,8 +45531,8 @@
}
function getEntityNameForDecoratorMetadataFromTypeList(types) {
var commonEntityName;
- for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
- var typeNode = types_16[_i];
+ for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
+ var typeNode = types_17[_i];
while (typeNode.kind === 177) {
typeNode = typeNode.type;
}
@@ -45092,7 +45767,7 @@
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 279:
+ case 284:
case 244:
case 218:
case 246:
@@ -45181,8 +45856,8 @@
return;
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];
+ for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
+ var typeParameter = typeParameters_3[_i];
if (!isTypeParameterUnused(typeParameter))
continue;
var name = ts.idText(typeParameter.name);
@@ -45420,7 +46095,7 @@
return;
}
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 && ts.isExternalOrCommonJsModule(parent)) {
+ if (parent.kind === 284 && ts.isExternalOrCommonJsModule(parent)) {
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
}
@@ -45432,7 +46107,7 @@
return;
}
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) {
+ if (parent.kind === 284 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) {
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));
}
}
@@ -45460,7 +46135,7 @@
(container.kind === 218 && ts.isFunctionLike(container.parent) ||
container.kind === 245 ||
container.kind === 244 ||
- container.kind === 279);
+ container.kind === 284);
if (!namesShareScope) {
var name = symbolToString(localDeclarationSymbol);
error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
@@ -45536,7 +46211,7 @@
}
}
if (node.kind === 186) {
- if (node.parent.kind === 184 && languageVersion < 6) {
+ if (node.parent.kind === 184 && languageVersion < 7) {
checkExternalEmitHelpers(node, 4);
}
if (node.propertyName && node.propertyName.kind === 149) {
@@ -45545,7 +46220,7 @@
var parent = node.parent.parent;
var parentType = getTypeForBindingElementParent(parent);
var name = node.propertyName || node.name;
- if (!ts.isBindingPattern(name) && parentType) {
+ if (parentType && !ts.isBindingPattern(name)) {
var exprType = getLiteralTypeFromPropertyName(name);
if (isTypeUsableAsPropertyName(exprType)) {
var nameText = getPropertyNameFromType(exprType);
@@ -45716,7 +46391,7 @@
checkGrammarForInOrForOfStatement(node);
if (node.awaitModifier) {
var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
- if ((functionFlags & (4 | 2)) === 2 && languageVersion < 6) {
+ if ((functionFlags & (4 | 2)) === 2 && languageVersion < 7) {
checkExternalEmitHelpers(node, 16384);
}
}
@@ -46021,7 +46696,7 @@
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);
if (promisedType) {
- checkTypeAssignableTo(awaitedType, promisedType, node);
+ checkTypeAssignableToAndOptionallyElaborate(awaitedType, promisedType, node, node.expression);
}
}
else {
@@ -46542,8 +47217,8 @@
for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
var base = baseTypes_2[_i];
var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
- for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) {
- var prop = properties_7[_a];
+ for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
+ var prop = properties_6[_a];
var existing = seen.get(prop.escapedName);
if (!existing) {
seen.set(prop.escapedName, { prop: prop, containingType: base });
@@ -46801,16 +47476,13 @@
checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
checkExportsOnMergedDeclarations(node);
computeEnumMemberValues(node);
- var enumIsConst = ts.isEnumConst(node);
- if (compilerOptions.isolatedModules && enumIsConst && node.flags & 4194304) {
- error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided);
- }
var enumSymbol = getSymbolOfNode(node);
var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
if (node === firstDeclaration) {
if (enumSymbol.declarations.length > 1) {
+ var enumIsConst_1 = ts.isEnumConst(node);
ts.forEach(enumSymbol.declarations, function (decl) {
- if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) {
+ if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
}
});
@@ -46887,8 +47559,8 @@
checkExportsOnMergedDeclarations(node);
var symbol = getSymbolOfNode(node);
if (symbol.flags & 512
- && symbol.declarations.length > 1
&& !inAmbientContext
+ && symbol.declarations.length > 1
&& isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
if (firstNonAmbientClassOrFunc) {
@@ -47011,7 +47683,7 @@
return false;
}
var inAmbientExternalModule = node.parent.kind === 245 && ts.isAmbientModule(node.parent.parent);
- if (node.parent.kind !== 279 && !inAmbientExternalModule) {
+ if (node.parent.kind !== 284 && !inAmbientExternalModule) {
error(moduleName, node.kind === 255 ?
ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
@@ -47122,7 +47794,7 @@
var inAmbientExternalModule = node.parent.kind === 245 && ts.isAmbientModule(node.parent.parent);
var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 &&
!node.moduleSpecifier && node.flags & 4194304;
- if (node.parent.kind !== 279 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
+ if (node.parent.kind !== 284 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
}
}
@@ -47138,7 +47810,7 @@
}
}
function checkGrammarModuleElementContext(node, errorMessage) {
- var isInAppropriateContext = node.parent.kind === 279 || node.parent.kind === 245 || node.parent.kind === 244;
+ var isInAppropriateContext = node.parent.kind === 284 || node.parent.kind === 245 || node.parent.kind === 244;
if (!isInAppropriateContext) {
grammarErrorOnFirstToken(node, errorMessage);
}
@@ -47164,7 +47836,7 @@
if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) {
return;
}
- var container = node.parent.kind === 279 ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 ? node.parent : node.parent.parent;
if (container.kind === 244 && !ts.isAmbientModule(container)) {
if (node.isExportEquals) {
error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
@@ -47248,9 +47920,14 @@
!!declaration.body;
}
function checkSourceElement(node) {
- if (!node) {
- return;
+ if (node) {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
+ checkSourceElementWorker(node);
+ currentNode = saveCurrentNode;
+ }
}
+ function checkSourceElementWorker(node) {
if (ts.isInJSFile(node)) {
ts.forEach(node.jsDoc, function (_a) {
var tags = _a.tags;
@@ -47318,31 +47995,31 @@
return checkInferType(node);
case 183:
return checkImportType(node);
- case 295:
+ case 300:
return checkJSDocAugmentsTag(node);
- case 304:
- case 297:
+ case 309:
+ case 302:
return checkJSDocTypeAliasTag(node);
- case 303:
+ case 308:
return checkJSDocTemplateTag(node);
- case 302:
+ case 307:
return checkJSDocTypeTag(node);
- case 299:
+ case 304:
return checkJSDocParameterTag(node);
- case 289:
+ case 294:
checkJSDocFunctionType(node);
- case 287:
- case 286:
- case 284:
- case 285:
case 292:
+ case 291:
+ case 289:
+ case 290:
+ case 297:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 290:
+ case 295:
checkJSDocVariadicType(node);
return;
- case 283:
+ case 288:
return checkSourceElement(node.type);
case 180:
return checkIndexedAccessType(node);
@@ -47477,10 +48154,13 @@
}
function checkDeferredNodes(context) {
var links = getNodeLinks(context);
- if (!links.deferredNodes) {
- return;
+ if (links.deferredNodes) {
+ links.deferredNodes.forEach(checkDeferredNode);
}
- links.deferredNodes.forEach(function (node) {
+ }
+ function checkDeferredNode(node) {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
switch (node.kind) {
case 196:
case 197:
@@ -47502,7 +48182,7 @@
checkJsxElementDeferred(node);
break;
}
- });
+ currentNode = saveCurrentNode;
}
function checkSourceFile(node) {
ts.performance.mark("beforeCheck");
@@ -47612,7 +48292,7 @@
copySymbols(location.locals, meaning);
}
switch (location.kind) {
- case 279:
+ case 284:
if (!ts.isExternalOrCommonJsModule(location))
break;
case 244:
@@ -47806,10 +48486,10 @@
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 299) {
+ if (entityName.parent.kind === 304) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 150 && entityName.parent.parent.kind === 303) {
+ if (entityName.parent.kind === 150 && entityName.parent.parent.kind === 308) {
ts.Debug.assert(!ts.isInJSFile(entityName));
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -47849,7 +48529,7 @@
return undefined;
}
function getSymbolAtLocation(node) {
- if (node.kind === 279) {
+ if (node.kind === 284) {
return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
}
var parent = node.parent;
@@ -48132,7 +48812,7 @@
}
var parentSymbol_1 = getParentOfSymbol(symbol);
if (parentSymbol_1) {
- if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 279) {
+ if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 284) {
var symbolFile = parentSymbol_1.valueDeclaration;
var referenceFile = ts.getSourceFileOfNode(node);
var symbolIsUmdExport = symbolFile !== referenceFile;
@@ -48154,7 +48834,7 @@
return undefined;
}
function isSymbolOfDeclarationWithCollidingName(symbol) {
- if (symbol.flags & 418) {
+ if (symbol.flags & 418 && !ts.isSourceFile(symbol.valueDeclaration)) {
var links = getSymbolLinks(symbol);
if (links.isDeclarationWithCollidingName === undefined) {
var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
@@ -48221,7 +48901,7 @@
}
function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
- if (node === undefined || node.parent.kind !== 279 || !ts.isInternalModuleImportEqualsDeclaration(node)) {
+ if (node === undefined || node.parent.kind !== 284 || !ts.isInternalModuleImportEqualsDeclaration(node)) {
return false;
}
var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
@@ -48607,7 +49287,7 @@
break;
}
}
- if (current.valueDeclaration && current.valueDeclaration.kind === 279 && current.flags & 512) {
+ if (current.valueDeclaration && current.valueDeclaration.kind === 284 && current.flags & 512) {
return false;
}
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
@@ -48639,7 +49319,7 @@
if (!moduleSymbol) {
return undefined;
}
- return ts.getDeclarationOfKind(moduleSymbol, 279);
+ return ts.getDeclarationOfKind(moduleSymbol, 284);
}
function initializeTypeChecker() {
for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
@@ -48703,7 +49383,7 @@
if (autoArrayType === emptyObjectType) {
autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
}
- globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", 1);
+ globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", 1) || globalArrayType;
anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
globalThisType = getGlobalTypeOrUndefined("ThisType", 1);
if (augmentations) {
@@ -48735,8 +49415,8 @@
}
else {
var list = ts.arrayFrom(conflictingSymbols.keys()).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)));
+ diagnostics.add(ts.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(ts.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;
@@ -48852,7 +49532,7 @@
else if (flags & 256) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
}
- else if (node.parent.kind === 245 || node.parent.kind === 279) {
+ else if (node.parent.kind === 245 || node.parent.kind === 284) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
}
else if (flags & 128) {
@@ -48875,7 +49555,7 @@
else if (flags & 256) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
}
- else if (node.parent.kind === 245 || node.parent.kind === 279) {
+ else if (node.parent.kind === 245 || node.parent.kind === 284) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
}
else if (node.kind === 151) {
@@ -48919,7 +49599,7 @@
flags |= 1;
break;
case 80:
- var container = node.parent.kind === 279 ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 ? node.parent : node.parent.parent;
if (container.kind === 244 && !ts.isAmbientModule(container)) {
return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
}
@@ -49038,7 +49718,7 @@
case 151:
return false;
default:
- if (node.parent.kind === 245 || node.parent.kind === 279) {
+ if (node.parent.kind === 245 || node.parent.kind === 284) {
return false;
}
switch (node.kind) {
@@ -49126,10 +49806,10 @@
var nonSimpleParameters = getNonSimpleParameters(node.parameters);
if (ts.length(nonSimpleParameters)) {
ts.forEach(nonSimpleParameters, function (parameter) {
- addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
+ ts.addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
});
var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); });
- addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
+ ts.addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
return true;
}
}
@@ -49528,6 +50208,11 @@
return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
}
}
+ else if (node.operator === 133) {
+ if (node.type.kind !== 169 && node.type.kind !== 170) {
+ return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(139));
+ }
+ }
}
function checkGrammarForInvalidDynamicName(node, message) {
if (isNonBindableDynamicName(node)) {
@@ -49882,7 +50567,7 @@
if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) {
return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
}
- if (node.parent.kind === 218 || node.parent.kind === 245 || node.parent.kind === 279) {
+ if (node.parent.kind === 218 || node.parent.kind === 245 || node.parent.kind === 284) {
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);
@@ -49917,7 +50602,7 @@
var literalType = ts.isLiteralTypeNode(node.parent) ||
ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
if (!literalType) {
- if (languageVersion < 6) {
+ if (languageVersion < 7) {
if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) {
return true;
}
@@ -50064,10 +50749,11 @@
return createLiteralFromNode(value);
}
ts.createLiteral = createLiteral;
- function createNumericLiteral(value) {
+ function createNumericLiteral(value, numericLiteralFlags) {
+ if (numericLiteralFlags === void 0) { numericLiteralFlags = 0; }
var node = createSynthesizedNode(8);
node.text = value;
- node.numericLiteralFlags = 0;
+ node.numericLiteralFlags = numericLiteralFlags;
return node;
}
ts.createNumericLiteral = createNumericLiteral;
@@ -51890,27 +52576,27 @@
}
ts.updateExternalModuleReference = updateExternalModuleReference;
function createJSDocTypeExpression(type) {
- var node = createSynthesizedNode(283);
+ var node = createSynthesizedNode(288);
node.type = type;
return node;
}
ts.createJSDocTypeExpression = createJSDocTypeExpression;
function createJSDocTypeTag(typeExpression, comment) {
- var tag = createJSDocTag(302, "type");
+ var tag = createJSDocTag(307, "type");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
}
ts.createJSDocTypeTag = createJSDocTypeTag;
function createJSDocReturnTag(typeExpression, comment) {
- var tag = createJSDocTag(300, "returns");
+ var tag = createJSDocTag(305, "returns");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
}
ts.createJSDocReturnTag = createJSDocReturnTag;
function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
- var tag = createJSDocTag(299, "param");
+ var tag = createJSDocTag(304, "param");
tag.typeExpression = typeExpression;
tag.name = name;
tag.isBracketed = isBracketed;
@@ -51919,7 +52605,7 @@
}
ts.createJSDocParamTag = createJSDocParamTag;
function createJSDocComment(comment, tags) {
- var node = createSynthesizedNode(291);
+ var node = createSynthesizedNode(296);
node.comment = comment;
node.tags = tags;
return node;
@@ -51998,6 +52684,28 @@
return node;
}
ts.createJsxFragment = createJsxFragment;
+ function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
+ var node = createSynthesizedNode(11);
+ node.text = text;
+ node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
+ return node;
+ }
+ ts.createJsxText = createJsxText;
+ function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
+ return node.text !== text
+ || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
+ ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
+ : node;
+ }
+ ts.updateJsxText = updateJsxText;
+ function createJsxOpeningFragment() {
+ return createSynthesizedNode(265);
+ }
+ ts.createJsxOpeningFragment = createJsxOpeningFragment;
+ function createJsxJsxClosingFragment() {
+ return createSynthesizedNode(266);
+ }
+ ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment;
function updateJsxFragment(node, openingFragment, children, closingFragment) {
return node.openingFragment !== openingFragment
|| node.children !== children
@@ -52172,7 +52880,7 @@
(typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
(libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
(hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
- var updated = createSynthesizedNode(279);
+ var updated = createSynthesizedNode(284);
updated.flags |= node.flags;
updated.statements = createNodeArray(statements);
updated.endOfFileToken = node.endOfFileToken;
@@ -52246,28 +52954,28 @@
}
ts.getMutableClone = getMutableClone;
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(307);
+ var node = createSynthesizedNode(312);
node.original = original;
setTextRange(node, original);
return node;
}
ts.createNotEmittedStatement = createNotEmittedStatement;
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(311);
+ var node = createSynthesizedNode(316);
node.emitNode = {};
node.original = original;
return node;
}
ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker;
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(310);
+ var node = createSynthesizedNode(315);
node.emitNode = {};
node.original = original;
return node;
}
ts.createMergeDeclarationMarker = createMergeDeclarationMarker;
function createPartiallyEmittedExpression(expression, original) {
- var node = createSynthesizedNode(308);
+ var node = createSynthesizedNode(313);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -52283,7 +52991,7 @@
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
function flattenCommaElements(node) {
if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
- if (node.kind === 309) {
+ if (node.kind === 314) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27) {
@@ -52293,7 +53001,7 @@
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(309);
+ var node = createSynthesizedNode(314);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -52306,33 +53014,195 @@
ts.updateCommaList = updateCommaList;
function createBundle(sourceFiles, prepends) {
if (prepends === void 0) { prepends = ts.emptyArray; }
- var node = ts.createNode(280);
+ var node = ts.createNode(285);
node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, map) {
- var node = ts.createNode(281);
+ var allUnscopedEmitHelpers;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
+ ts.valuesHelper,
+ ts.readHelper,
+ ts.spreadHelper,
+ ts.restHelper,
+ ts.decorateHelper,
+ ts.metadataHelper,
+ ts.paramHelper,
+ ts.awaiterHelper,
+ ts.assignHelper,
+ ts.awaitHelper,
+ ts.asyncGeneratorHelper,
+ ts.asyncDelegator,
+ ts.asyncValues,
+ ts.extendsHelper,
+ ts.templateObjectHelper,
+ ts.generatorHelper,
+ ts.importStarHelper,
+ ts.importDefaultHelper
+ ], function (helper) { return helper.name; }));
+ }
+ function createUnparsedSource() {
+ var node = ts.createNode(286);
+ node.prologues = ts.emptyArray;
+ node.referencedFiles = ts.emptyArray;
+ node.libReferenceDirectives = ts.emptyArray;
+ node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
+ return node;
+ }
+ function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
+ var node = createUnparsedSource();
+ var stripInternal;
+ var bundleFileInfo;
if (!ts.isString(textOrInputFiles)) {
ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
- node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath;
+ node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
Object.defineProperties(node, {
text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
});
+ if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
+ node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
+ ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
+ stripInternal = mapTextOrStripInternal;
+ bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
+ if (node.oldFileOfCurrentEmit) {
+ parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo));
+ return node;
+ }
+ }
}
else {
+ node.fileName = "";
node.text = textOrInputFiles;
node.sourceMapPath = mapPathOrType;
- node.sourceMapText = map;
+ node.sourceMapText = mapTextOrStripInternal;
}
+ ts.Debug.assert(!node.oldFileOfCurrentEmit);
+ parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
return node;
}
ts.createUnparsedSourceFile = createUnparsedSourceFile;
- function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapText) {
- var node = ts.createNode(282);
+ function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
+ var prologues;
+ var helpers;
+ var referencedFiles;
+ var typeReferenceDirectives;
+ var libReferenceDirectives;
+ var texts;
+ for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "prologue":
+ (prologues || (prologues = [])).push(createUnparsedNode(section, node));
+ break;
+ case "emitHelpers":
+ (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
+ break;
+ case "no-default-lib":
+ node.hasNoDefaultLib = true;
+ break;
+ case "reference":
+ (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "type":
+ (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
+ break;
+ case "lib":
+ (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "prepend":
+ var prependNode = createUnparsedNode(section, node);
+ var prependTexts = void 0;
+ for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
+ var text = _c[_b];
+ if (!stripInternal || text.kind !== "internal") {
+ (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
+ }
+ }
+ prependNode.texts = prependTexts || ts.emptyArray;
+ (texts || (texts = [])).push(prependNode);
+ break;
+ case "internal":
+ if (stripInternal)
+ break;
+ case "text":
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.prologues = prologues || ts.emptyArray;
+ node.helpers = helpers;
+ node.referencedFiles = referencedFiles || ts.emptyArray;
+ node.typeReferenceDirectives = typeReferenceDirectives;
+ node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
+ node.texts = texts || [createUnparsedNode({ kind: "text", pos: 0, end: node.text.length }, node)];
+ }
+ function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
+ ts.Debug.assert(!!node.oldFileOfCurrentEmit);
+ var texts;
+ var syntheticReferences;
+ for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "internal":
+ case "text":
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ case "no-default-lib":
+ case "reference":
+ case "type":
+ case "lib":
+ (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
+ break;
+ case "prologue":
+ case "emitHelpers":
+ case "prepend":
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.texts = texts || ts.emptyArray;
+ node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
+ node.syntheticReferences = syntheticReferences;
+ return node;
+ }
+ function mapBundleFileSectionKindToSyntaxKind(kind) {
+ switch (kind) {
+ case "prologue": return 279;
+ case "prepend": return 280;
+ case "internal": return 282;
+ case "text": return 281;
+ case "emitHelpers":
+ case "no-default-lib":
+ case "reference":
+ case "type":
+ case "lib":
+ return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
+ default:
+ return ts.Debug.assertNever(kind);
+ }
+ }
+ function createUnparsedNode(section, parent) {
+ var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ return node;
+ }
+ function createUnparsedSyntheticReference(section, parent) {
+ var node = ts.createNode(283, section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ node.section = section;
+ return node;
+ }
+ function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
+ var node = ts.createNode(287);
if (!ts.isString(javascriptTextOrReadFileText)) {
var cache_1 = ts.createMap();
var textGetter_1 = function (path) {
@@ -52349,15 +53219,25 @@
var result = textGetter_1(path);
return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
};
+ var buildInfo_1;
+ var getAndCacheBuildInfo_1 = function (getText) {
+ if (buildInfo_1 === undefined) {
+ var result = getText();
+ buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
+ }
+ return buildInfo_1 || undefined;
+ };
node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath;
node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath;
+ node.buildInfoPath = declarationMapTextOrBuildInfoPath;
Object.defineProperties(node, {
javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
- declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } }
+ declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
+ buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
});
}
else {
@@ -52366,7 +53246,12 @@
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
node.declarationText = declarationTextOrJavascriptPath;
node.declarationMapPath = declarationMapPath;
- node.declarationMapText = declarationMapText;
+ node.declarationMapText = declarationMapTextOrBuildInfoPath;
+ node.javascriptPath = javascriptPath;
+ node.declarationPath = declarationPath,
+ node.buildInfoPath = buildInfoPath;
+ node.buildInfo = buildInfo;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
}
return node;
}
@@ -52470,10 +53355,10 @@
function getOrCreateEmitNode(node) {
if (!node.emitNode) {
if (ts.isParseTreeNode(node)) {
- if (node.kind === 279) {
+ if (node.kind === 284) {
return node.emitNode = { annotatedNodes: [node] };
}
- var sourceFile = ts.getSourceFileOfNode(node);
+ var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
}
node.emitNode = {};
@@ -52710,7 +53595,7 @@
ts.nullTransformationContext = {
enableEmitNotification: ts.noop,
enableSubstitution: ts.noop,
- endLexicalEnvironment: function () { return undefined; },
+ endLexicalEnvironment: ts.returnUndefined,
getCompilerOptions: ts.notImplemented,
getEmitHost: ts.notImplemented,
getEmitResolver: ts.notImplemented,
@@ -52843,36 +53728,36 @@
return ts.setEmitFlags(ts.createIdentifier(name), 4096 | 2);
}
ts.getHelperName = getHelperName;
- var valuesHelper = {
+ ts.valuesHelper = {
name: "typescript:values",
scoped: false,
text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };"
};
function createValuesHelper(context, expression, location) {
- context.requestEmitHelper(valuesHelper);
+ context.requestEmitHelper(ts.valuesHelper);
return ts.setTextRange(ts.createCall(getHelperName("__values"), undefined, [expression]), location);
}
ts.createValuesHelper = createValuesHelper;
- var readHelper = {
+ ts.readHelper = {
name: "typescript:read",
scoped: false,
text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };"
};
function createReadHelper(context, iteratorRecord, count, location) {
- context.requestEmitHelper(readHelper);
+ context.requestEmitHelper(ts.readHelper);
return ts.setTextRange(ts.createCall(getHelperName("__read"), undefined, count !== undefined
? [iteratorRecord, ts.createLiteral(count)]
: [iteratorRecord]), location);
}
ts.createReadHelper = createReadHelper;
- var spreadHelper = {
+ ts.spreadHelper = {
name: "typescript:spread",
scoped: false,
text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
};
function createSpreadHelper(context, argumentList, location) {
- context.requestEmitHelper(readHelper);
- context.requestEmitHelper(spreadHelper);
+ context.requestEmitHelper(ts.readHelper);
+ context.requestEmitHelper(ts.spreadHelper);
return ts.setTextRange(ts.createCall(getHelperName("__spread"), undefined, argumentList), location);
}
ts.createSpreadHelper = createSpreadHelper;
@@ -53033,27 +53918,27 @@
function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) {
var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
if (property === firstAccessor) {
- var properties_8 = [];
+ var properties_7 = [];
if (getAccessor) {
var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body);
ts.setTextRange(getterFunction, getAccessor);
ts.setOriginalNode(getterFunction, getAccessor);
var getter = ts.createPropertyAssignment("get", getterFunction);
- properties_8.push(getter);
+ properties_7.push(getter);
}
if (setAccessor) {
var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body);
ts.setTextRange(setterFunction, setAccessor);
ts.setOriginalNode(setterFunction, setAccessor);
var setter = ts.createPropertyAssignment("set", setterFunction);
- properties_8.push(setter);
+ properties_7.push(setter);
}
- properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
- properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
+ properties_7.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
+ properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [
receiver,
createExpressionForPropertyName(property.name),
- ts.createObjectLiteral(properties_8, multiLine)
+ ts.createObjectLiteral(properties_7, multiLine)
]), firstAccessor);
return ts.aggregateTransformFlags(expression);
}
@@ -53476,7 +54361,7 @@
case 190:
case 189:
case 213:
- case 308:
+ case 313:
node = node.expression;
continue;
}
@@ -53492,7 +54377,7 @@
ts.parenthesizeConciseBody = parenthesizeConciseBody;
function isCommaSequence(node) {
return node.kind === 204 && node.operatorToken.kind === 27 ||
- node.kind === 309;
+ node.kind === 314;
}
ts.isCommaSequence = isCommaSequence;
function isOuterExpression(node, kinds) {
@@ -53504,7 +54389,7 @@
case 212:
case 213:
return (kinds & 2) !== 0;
- case 308:
+ case 313:
return (kinds & 4) !== 0;
}
return false;
@@ -53541,7 +54426,7 @@
case 194: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 212: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 213: return ts.updateNonNullExpression(outerExpression, expression);
- case 308: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 313: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
function isIgnorableParen(node) {
@@ -54174,11 +55059,11 @@
return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression));
case 278:
return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
- case 279:
+ case 284:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
- case 308:
+ case 313:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 309:
+ case 314:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
return node;
@@ -54216,7 +55101,7 @@
case 220:
case 210:
case 236:
- case 307:
+ case 312:
break;
case 148:
result = reduceNode(node.left, cbNode, result);
@@ -54578,13 +55463,13 @@
result = reduceNode(node.name, cbNode, result);
result = reduceNode(node.initializer, cbNode, result);
break;
- case 279:
+ case 284:
result = reduceNodes(node.statements, cbNodes, result);
break;
- case 308:
+ case 313:
result = reduceNode(node.expression, cbNode, result);
break;
- case 309:
+ case 314:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -54598,8 +55483,8 @@
return statements;
}
return ts.isNodeArray(statements)
- ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements)
- : ts.addStatementsAfterPrologue(statements, declarations);
+ ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements)
+ : ts.insertStatementsAfterStandardPrologue(statements, declarations);
}
ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
function liftToBlock(nodes) {
@@ -54830,7 +55715,7 @@
}
exit();
}
- function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) {
+ function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
var _a;
ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
@@ -54839,6 +55724,14 @@
var nameIndexToNewNameIndexMap;
var mappingIterator = decodeMappings(map.mappings);
for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) {
+ if (end && (raw.generatedLine > end.line ||
+ (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
+ break;
+ }
+ if (start && (raw.generatedLine < start.line ||
+ (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
+ continue;
+ }
var newSourceIndex = void 0;
var newSourceLine = void 0;
var newSourceCharacter = void 0;
@@ -54865,8 +55758,10 @@
}
}
}
- var newGeneratedLine = raw.generatedLine + generatedLine;
- var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter;
+ var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
+ var newGeneratedLine = rawGeneratedLine + generatedLine;
+ var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
+ var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
}
exit();
@@ -55313,7 +56208,7 @@
function chainBundle(transformSourceFile) {
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- return node.kind === 279 ? transformSourceFile(node) : transformBundle(node);
+ return node.kind === 284 ? transformSourceFile(node) : transformBundle(node);
}
function transformBundle(node) {
return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
@@ -55690,8 +56585,8 @@
if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
if (flattenContext.level >= 1
- && !(element.transformFlags & (131072 | 262144))
- && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 | 262144))
+ && !(element.transformFlags & (4096 | 8192))
+ && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (4096 | 8192))
&& !ts.isComputedPropertyName(propertyName)) {
bindingElements = ts.append(bindingElements, element);
}
@@ -55738,7 +56633,7 @@
for (var i = 0; i < numElements; i++) {
var element = elements[i];
if (flattenContext.level >= 1) {
- if (element.transformFlags & 262144) {
+ if (element.transformFlags & 8192) {
var temp = ts.createTempVariable(undefined);
if (flattenContext.hoistTempVariables) {
flattenContext.context.hoistVariableDeclaration(temp);
@@ -55827,13 +56722,13 @@
function makeAssignmentElement(name) {
return name;
}
- var restHelper = {
+ ts.restHelper = {
name: "typescript:rest",
scoped: false,
text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
};
function createRestCall(context, value, elements, computedTempVariables, location) {
- context.requestEmitHelper(restHelper);
+ context.requestEmitHelper(ts.restHelper);
var propertyNames = [];
var computedTempVariableOffset = 0;
for (var i = 0; i < elements.length - 1; i++) {
@@ -55883,14 +56778,14 @@
var pendingExpressions;
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- if (node.kind === 280) {
+ if (node.kind === 285) {
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 === 282) {
+ if (prepend.kind === 287) {
return ts.createUnparsedSourceFile(prepend, "js");
}
return prepend;
@@ -55921,7 +56816,7 @@
}
function onBeforeVisitNode(node) {
switch (node.kind) {
- case 279:
+ case 284:
case 246:
case 245:
case 218:
@@ -55953,9 +56848,6 @@
if (node.transformFlags & 1) {
return visitTypeScript(node);
}
- else if (node.transformFlags & 2) {
- return ts.visitEachChild(node, visitor, context);
- }
return node;
}
function sourceElementVisitor(node) {
@@ -55975,7 +56867,7 @@
function visitEllidableStatement(node) {
var parsed = ts.getParseTreeNode(node);
if (parsed !== node) {
- if (node.transformFlags & 2) {
+ if (node.transformFlags & 1) {
return ts.visitEachChild(node, visitor, context);
}
return node;
@@ -56007,9 +56899,6 @@
else if (node.transformFlags & 1 || ts.hasModifier(node, 1)) {
return visitTypeScript(node);
}
- else if (node.transformFlags & 2) {
- return ts.visitEachChild(node, visitor, context);
- }
return node;
}
function classElementVisitor(node) {
@@ -56041,7 +56930,7 @@
return node;
}
function visitTypeScript(node) {
- if (ts.hasModifier(node, 2) && ts.isStatement(node)) {
+ if (ts.isStatement(node) && ts.hasModifier(node, 2)) {
return ts.createNotEmittedStatement(node);
}
switch (node.kind) {
@@ -56141,7 +57030,7 @@
case 248:
return visitImportEqualsDeclaration(node);
default:
- return ts.Debug.failBadSyntaxKind(node);
+ return ts.visitEachChild(node, visitor, context);
}
}
function visitSourceFile(node) {
@@ -56184,7 +57073,19 @@
facts |= 128;
return facts;
}
+ function hasTypeScriptClassSyntax(node) {
+ return !!(node.transformFlags & 1024);
+ }
+ function isClassLikeDeclarationWithTypeScriptSyntax(node) {
+ return ts.some(node.decorators)
+ || ts.some(node.typeParameters)
+ || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
+ || ts.some(node.members, hasTypeScriptClassSyntax);
+ }
function visitClassDeclaration(node) {
+ if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1))) {
+ return ts.visitEachChild(node, visitor, context);
+ }
var savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
var staticProperties = getInitializedProperties(node, true);
@@ -56217,7 +57118,7 @@
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 | 384);
statements.push(statement);
- ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
var iife = ts.createImmediatelyInvokedArrowFunction(statements);
ts.setEmitFlags(iife, 33554432);
var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([
@@ -56278,6 +57179,9 @@
return statement;
}
function visitClassExpression(node) {
+ if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
+ return ts.visitEachChild(node, visitor, context);
+ }
var savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
var staticProperties = getInitializedProperties(node, true);
@@ -56320,7 +57224,7 @@
var constructor = ts.getFirstConstructorWithBody(node);
var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty);
var hasParameterPropertyAssignments = constructor &&
- constructor.transformFlags & 4096 &&
+ constructor.transformFlags & 1024 &&
ts.forEach(constructor.parameters, isParameterWithPropertyAssignment);
if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) {
return ts.visitEachChild(constructor, visitor, context);
@@ -56400,8 +57304,8 @@
&& member.initializer !== undefined;
}
function addInitializedPropertyStatements(statements, properties, receiver) {
- for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
- var property = properties_9[_i];
+ for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
+ var property = properties_8[_i];
var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver));
ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
ts.setCommentRange(statement, property);
@@ -56411,8 +57315,8 @@
}
function generateInitializedPropertyExpressions(properties, receiver) {
var expressions = [];
- for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) {
- var property = properties_10[_i];
+ for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
+ var property = properties_9[_i];
var expression = transformInitializedProperty(property, receiver);
ts.startOnNewLine(expression);
ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
@@ -56447,11 +57351,14 @@
var decorators;
if (node) {
var parameters = node.parameters;
- for (var i = 0; i < parameters.length; i++) {
- var parameter = parameters[i];
+ var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
+ var firstParameterOffset = firstParameterIsThis ? 1 : 0;
+ var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
+ for (var i = 0; i < numParameters; i++) {
+ var parameter = parameters[i + firstParameterOffset];
if (decorators || parameter.decorators) {
if (!decorators) {
- decorators = new Array(parameters.length);
+ decorators = new Array(numParameters);
}
decorators[i] = parameter.decorators;
}
@@ -56779,8 +57686,12 @@
return serializeTypeList(node.types);
case 175:
return serializeTypeList([node.trueType, node.falseType]);
- case 167:
case 179:
+ if (node.operator === 133) {
+ return serializeTypeNode(node.type);
+ }
+ break;
+ case 167:
case 180:
case 181:
case 168:
@@ -56796,8 +57707,8 @@
}
function serializeTypeList(types) {
var serializedUnion;
- for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
- var typeNode = types_17[_i];
+ for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
+ var typeNode = types_18[_i];
while (typeNode.kind === 177) {
typeNode = typeNode.type;
}
@@ -56896,7 +57807,7 @@
return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object"));
}
function getGlobalBigIntNameWithFallback() {
- return languageVersion < 6
+ return languageVersion < 7
? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object"))
: ts.createIdentifier("BigInt");
}
@@ -56946,12 +57857,11 @@
}
}
function visitHeritageClause(node) {
- if (node.token === 86) {
- var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1);
- return ts.setTextRange(ts.createHeritageClause(86, types), node);
- }
+ if (node.token === 109) {
return undefined;
}
+ return ts.visitEachChild(node, visitor, context);
+ }
function visitExpressionWithTypeArguments(node) {
return ts.updateExpressionWithTypeArguments(node, undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
}
@@ -57034,13 +57944,14 @@
if (ts.parameterIsThisKeyword(node)) {
return undefined;
}
- var parameter = ts.createParameter(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
- ts.setOriginalNode(parameter, node);
- ts.setTextRange(parameter, ts.moveRangePastModifiers(node));
- ts.setCommentRange(parameter, node);
- ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node));
- ts.setEmitFlags(parameter.name, 32);
- return parameter;
+ var updated = ts.updateParameter(node, undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
+ if (updated !== node) {
+ ts.setCommentRange(updated, node);
+ ts.setTextRange(updated, ts.moveRangePastModifiers(node));
+ ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
+ ts.setEmitFlags(updated.name, 32);
+ }
+ return updated;
}
function visitVariableStatement(node) {
if (isExportOfNamespace(node)) {
@@ -57139,7 +58050,7 @@
var statements = [];
startLexicalEnvironment();
var members = ts.map(node.members, transformEnumMember);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
ts.addRange(statements, members);
currentNamespaceContainerName = savedCurrentNamespaceLocalName;
return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true);
@@ -57201,7 +58112,7 @@
function addVarForEnumOrModuleDeclaration(statements, node) {
var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
ts.createVariableDeclaration(ts.getLocalName(node, false, true))
- ], currentLexicalScope.kind === 279 ? 0 : 1));
+ ], currentLexicalScope.kind === 284 ? 0 : 1));
ts.setOriginalNode(statement, node);
recordEmittedDeclarationInScope(node);
if (isFirstEmittedDeclarationInScope(node)) {
@@ -57289,7 +58200,7 @@
var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
currentNamespaceContainerName = savedCurrentNamespaceContainerName;
currentNamespace = savedCurrentNamespace;
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
@@ -57542,7 +58453,7 @@
function trySubstituteNamespaceExportedName(node) {
if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
var container = resolver.getReferencedExportContainer(node, false);
- if (container && container.kind !== 279) {
+ if (container && container.kind !== 284) {
var substitute = (applicableSubstitutions & 2 && container.kind === 244) ||
(applicableSubstitutions & 8 && container.kind === 243);
if (substitute) {
@@ -57591,36 +58502,36 @@
argumentsArray.push(descriptor);
}
}
- context.requestEmitHelper(decorateHelper);
+ context.requestEmitHelper(ts.decorateHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"), undefined, argumentsArray), location);
}
- var decorateHelper = {
+ ts.decorateHelper = {
name: "typescript:decorate",
scoped: false,
priority: 2,
text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
};
function createMetadataHelper(context, metadataKey, metadataValue) {
- context.requestEmitHelper(metadataHelper);
+ context.requestEmitHelper(ts.metadataHelper);
return ts.createCall(ts.getHelperName("__metadata"), undefined, [
ts.createLiteral(metadataKey),
metadataValue
]);
}
- var metadataHelper = {
+ ts.metadataHelper = {
name: "typescript:metadata",
scoped: false,
priority: 3,
text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
};
function createParamHelper(context, expression, parameterOffset, location) {
- context.requestEmitHelper(paramHelper);
+ context.requestEmitHelper(ts.paramHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__param"), undefined, [
ts.createLiteral(parameterOffset),
expression
]), location);
}
- var paramHelper = {
+ ts.paramHelper = {
name: "typescript:param",
scoped: false,
priority: 4,
@@ -57654,7 +58565,7 @@
return visited;
}
function visitor(node) {
- if ((node.transformFlags & 16) === 0) {
+ if ((node.transformFlags & 32) === 0) {
return node;
}
switch (node.kind) {
@@ -57866,20 +58777,24 @@
}
var savedCapturedSuperProperties = capturedSuperProperties;
var savedHasSuperElementAccess = hasSuperElementAccess;
+ if (!isArrowFunction) {
capturedSuperProperties = ts.createUnderscoreEscapedMap();
hasSuperElementAccess = false;
+ }
var result;
if (!isArrowFunction) {
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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var emitSuperHelpers = languageVersion >= 2 && resolver.getNodeCheckFlags(node) & (4096 | 2048);
if (emitSuperHelpers) {
enableSubstitutionForAsyncMethodsWithSuper();
+ if (ts.hasEntries(capturedSuperProperties)) {
var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
- ts.addStatementsAfterPrologue(statements, [variableStatement]);
+ ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
+ }
}
var block = ts.createBlock(statements, true);
ts.setTextRange(block, node.body);
@@ -57905,8 +58820,10 @@
}
}
enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
+ if (!isArrowFunction) {
capturedSuperProperties = savedCapturedSuperProperties;
hasSuperElementAccess = savedHasSuperElementAccess;
+ }
return result;
}
function transformAsyncFunctionBodyWorker(body, start) {
@@ -58028,11 +58945,11 @@
names.forEach(function (_, key) {
var name = ts.unescapeLeadingUnderscores(key);
var getterAndSetter = [];
- getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, ts.createPropertyAccess(ts.createSuper(), name))));
+ getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4), name), 4))));
if (hasBinding) {
getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(undefined, undefined, [
ts.createParameter(undefined, undefined, undefined, "v", undefined, undefined, undefined)
- ], undefined, undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v")))));
+ ], undefined, undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4), name), 4), ts.createIdentifier("v")))));
}
accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter)));
});
@@ -58044,14 +58961,14 @@
], 2));
}
ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
- var awaiterHelper = {
+ ts.awaiterHelper = {
name: "typescript:awaiter",
scoped: false,
priority: 5,
text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
};
function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
- context.requestEmitHelper(awaiterHelper);
+ context.requestEmitHelper(ts.awaiterHelper);
var generatorFunc = ts.createFunctionExpression(undefined, ts.createToken(40), undefined, undefined, [], undefined, body);
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 | 524288;
return ts.createCall(ts.getHelperName("__awaiter"), undefined, [
@@ -58074,7 +58991,7 @@
})(ts || (ts = {}));
var ts;
(function (ts) {
- function transformESNext(context) {
+ function transformES2018(context) {
var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
var resolver = context.getEmitResolver();
var compilerOptions = context.getCompilerOptions();
@@ -58111,7 +59028,7 @@
return node;
}
function visitorWorker(node, noDestructuringValue) {
- if ((node.transformFlags & 8) === 0) {
+ if ((node.transformFlags & 16) === 0) {
return node;
}
switch (node.kind) {
@@ -58155,8 +59072,6 @@
return visitExpressionStatement(node);
case 195:
return visitParenthesizedExpression(node, noDestructuringValue);
- case 274:
- return visitCatchClause(node);
case 189:
if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98) {
capturedSuperProperties.set(node.name.escapedText, true);
@@ -58230,7 +59145,7 @@
return objects;
}
function visitObjectLiteralExpression(node) {
- if (node.transformFlags & 262144) {
+ if (node.transformFlags & 8192) {
var objects = chunkObjectLiteralElements(node.properties);
if (objects.length && objects[0].kind !== 188) {
objects.unshift(ts.createObjectLiteral());
@@ -58245,14 +59160,8 @@
function visitParenthesizedExpression(node, noDestructuringValue) {
return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
}
- function visitCatchClause(node) {
- if (!node.variableDeclaration) {
- return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
- }
- return ts.visitEachChild(node, visitor, context);
- }
function visitBinaryExpression(node, noDestructuringValue) {
- if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144) {
+ if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 8192) {
return ts.flattenDestructuringAssignment(node, visitor, context, 1, !noDestructuringValue);
}
else if (node.operatorToken.kind === 27) {
@@ -58261,7 +59170,7 @@
return ts.visitEachChild(node, visitor, context);
}
function visitVariableDeclaration(node) {
- if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144) {
+ if (ts.isBindingPattern(node.name) && node.name.transformFlags & 8192) {
return ts.flattenDestructuringBinding(node, visitor, context, 1);
}
return ts.visitEachChild(node, visitor, context);
@@ -58273,7 +59182,7 @@
return ts.visitEachChild(node, visitorNoDestructuringValue, context);
}
function visitForOfStatement(node, outermostLabeledStatement) {
- if (node.initializer.transformFlags & 262144) {
+ if (node.initializer.transformFlags & 8192) {
node = transformForOfStatementWithObjectRest(node);
}
if (node.awaitModifier) {
@@ -58360,7 +59269,7 @@
]));
}
function visitParameter(node) {
- if (node.transformFlags & 262144) {
+ if (node.transformFlags & 8192) {
return ts.updateParameter(node, undefined, undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
}
return ts.visitEachChild(node, visitor, context);
@@ -58447,10 +59356,10 @@
enableSubstitutionForAsyncMethodsWithSuper();
var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
- ts.addStatementsAfterPrologue(statements, [variableStatement]);
+ ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
}
statements.push(returnStatement);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var block = ts.updateBlock(node.body, statements);
if (emitSuperHelpers && hasSuperElementAccess) {
if (resolver.getNodeCheckFlags(node) & 4096) {
@@ -58476,7 +59385,7 @@
var leadingStatements = endLexicalEnvironment();
if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
var block = ts.convertToFunctionBody(body, true);
- ts.addStatementsAfterPrologue(statements, leadingStatements);
+ ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
ts.addRange(statements, block.statements.slice(statementOffset));
return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
}
@@ -58485,7 +59394,7 @@
function appendObjectRestAssignmentsIfNeeded(statements, node) {
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
- if (parameter.transformFlags & 262144) {
+ if (parameter.transformFlags & 8192) {
var temp = ts.getGeneratedNameForNode(parameter);
var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1, temp, false, true);
if (ts.some(declarations)) {
@@ -58590,8 +59499,8 @@
}
}
}
- ts.transformESNext = transformESNext;
- var assignHelper = {
+ ts.transformES2018 = transformES2018;
+ ts.assignHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
@@ -58601,27 +59510,27 @@
if (context.getCompilerOptions().target >= 2) {
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), undefined, attributesSegments);
}
- context.requestEmitHelper(assignHelper);
+ context.requestEmitHelper(ts.assignHelper);
return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments);
}
ts.createAssignHelper = createAssignHelper;
- var awaitHelper = {
+ ts.awaitHelper = {
name: "typescript:await",
scoped: false,
text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
};
function createAwaitHelper(context, expression) {
- context.requestEmitHelper(awaitHelper);
+ context.requestEmitHelper(ts.awaitHelper);
return ts.createCall(ts.getHelperName("__await"), undefined, [expression]);
}
- var asyncGeneratorHelper = {
+ ts.asyncGeneratorHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
};
function createAsyncGeneratorHelper(context, generatorFunc) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncGeneratorHelper);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncGeneratorHelper);
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144;
return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [
ts.createThis(),
@@ -58629,28 +59538,80 @@
generatorFunc
]);
}
- var asyncDelegator = {
+ ts.asyncDelegator = {
name: "typescript:asyncDelegator",
scoped: false,
text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
};
function createAsyncDelegatorHelper(context, expression, location) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncDelegator);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncDelegator);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location);
}
- var asyncValues = {
+ ts.asyncValues = {
name: "typescript:asyncValues",
scoped: false,
text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
};
function createAsyncValuesHelper(context, expression, location) {
- context.requestEmitHelper(asyncValues);
+ context.requestEmitHelper(ts.asyncValues);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"), undefined, [expression]), location);
}
})(ts || (ts = {}));
var ts;
(function (ts) {
+ function transformES2019(context) {
+ return ts.chainBundle(transformSourceFile);
+ function transformSourceFile(node) {
+ if (node.isDeclarationFile) {
+ return node;
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitor(node) {
+ if ((node.transformFlags & 8) === 0) {
+ return node;
+ }
+ switch (node.kind) {
+ case 274:
+ return visitCatchClause(node);
+ default:
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ function visitCatchClause(node) {
+ if (!node.variableDeclaration) {
+ return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ ts.transformES2019 = transformES2019;
+})(ts || (ts = {}));
+var ts;
+(function (ts) {
+ function transformESNext(context) {
+ return ts.chainBundle(transformSourceFile);
+ function transformSourceFile(node) {
+ if (node.isDeclarationFile) {
+ return node;
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitor(node) {
+ if ((node.transformFlags & 4) === 0) {
+ return node;
+ }
+ switch (node.kind) {
+ default:
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ }
+ ts.transformESNext = transformESNext;
+})(ts || (ts = {}));
+var ts;
+(function (ts) {
function transformJsx(context) {
var compilerOptions = context.getCompilerOptions();
var currentSourceFile;
@@ -58665,7 +59626,7 @@
return visited;
}
function visitor(node) {
- if (node.transformFlags & 4) {
+ if (node.transformFlags & 2) {
return visitorWorker(node);
}
else {
@@ -58771,7 +59732,7 @@
}
}
function visitJsxText(node) {
- var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, true));
+ var fixed = fixupWhitespaceAndDecodeEntities(node.text);
return fixed === undefined ? undefined : ts.createLiteral(fixed);
}
function fixupWhitespaceAndDecodeEntities(text) {
@@ -59116,7 +60077,7 @@
return ts.visitEachChild(node, visitor, context);
}
function visitor(node) {
- if ((node.transformFlags & 32) === 0) {
+ if ((node.transformFlags & 64) === 0) {
return node;
}
switch (node.kind) {
@@ -59202,11 +60163,11 @@
}
function enterSubtree(excludeFacts, includeFacts) {
var ancestorFacts = hierarchyFacts;
- hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383;
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 8191;
return ancestorFacts;
}
function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
- hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 | ancestorFacts;
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -8192 | ancestorFacts;
}
function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
return (hierarchyFacts & 4096) !== 0
@@ -59228,12 +60189,6 @@
return node;
}
}
- function functionBodyVisitor(node) {
- if (shouldVisitNode(node)) {
- return visitBlock(node, true);
- }
- return node;
- }
function callExpressionVisitor(node) {
if (node.kind === 98) {
return visitSuperKeyword(true);
@@ -59340,18 +60295,19 @@
}
function visitSourceFile(node) {
var ancestorFacts = enterSubtree(3968, 64);
+ var prologue = [];
var statements = [];
startLexicalEnvironment();
- var statementOffset = ts.addStandardPrologue(statements, node.statements, false);
- addCaptureThisForNodeIfNeeded(statements, node);
- statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor);
+ var statementOffset = ts.addStandardPrologue(prologue, node.statements, false);
+ statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor);
ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
if (taggedTemplateStringDeclarations) {
statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureThisForNodeIfNeeded(prologue, node);
exitSubtree(ancestorFacts, 0, 0);
- return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
+ return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
}
function visitSwitchStatement(node) {
if (convertedLoopState !== undefined) {
@@ -59390,6 +60346,9 @@
return ts.visitEachChild(node, visitor, context);
}
function visitThisKeyword(node) {
+ if (hierarchyFacts & 2) {
+ hierarchyFacts |= 16384;
+ }
if (convertedLoopState) {
if (hierarchyFacts & 2) {
convertedLoopState.containsLexicalThis = true;
@@ -59519,7 +60478,7 @@
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 | 384);
statements.push(statement);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true);
ts.setEmitFlags(block, 1536);
return block;
@@ -59532,7 +60491,7 @@
function addConstructor(statements, node, extendsClauseElement) {
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16278, 73);
+ var ancestorFacts = enterSubtree(8086, 73);
var constructor = ts.getFirstConstructorWithBody(node);
var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, ts.getInternalName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
@@ -59541,56 +60500,78 @@
ts.setEmitFlags(constructorFunction, 8);
}
statements.push(constructorFunction);
- exitSubtree(ancestorFacts, 49152, 0);
+ exitSubtree(ancestorFacts, 24576, 0);
convertedLoopState = savedConvertedLoopState;
}
function transformConstructorParameters(constructor, hasSynthesizedSuper) {
return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
|| [];
}
- function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
+ function createDefaultConstructorBody(node, isDerivedClass) {
var statements = [];
resumeLexicalEnvironment();
- var statementOffset = -1;
- if (hasSynthesizedSuper) {
- statementOffset = 0;
+ ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
+ if (isDerivedClass) {
+ statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
}
- else if (constructor) {
- statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, false);
+ var statementsArray = ts.createNodeArray(statements);
+ ts.setTextRange(statementsArray, node.members);
+ var block = ts.createBlock(statementsArray, true);
+ ts.setTextRange(block, node);
+ ts.setEmitFlags(block, 1536);
+ return block;
}
- if (constructor) {
+ function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
+ var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96;
+ if (!constructor)
+ return createDefaultConstructorBody(node, isDerivedClass);
+ var prologue = [];
+ var statements = [];
+ resumeLexicalEnvironment();
+ var statementOffset = 0;
+ if (!hasSynthesizedSuper)
+ statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, false);
addDefaultValueAssignmentsIfNeeded(statements, constructor);
addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
- if (!hasSynthesizedSuper) {
+ if (!hasSynthesizedSuper)
statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
+ var superCallExpression;
+ if (hasSynthesizedSuper) {
+ superCallExpression = createDefaultSuperCallOrThis();
}
- ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!");
+ else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
+ var firstStatement = constructor.body.statements[statementOffset];
+ if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
+ superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
}
- var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96;
- var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset);
- if (superCaptureStatus === 1 || superCaptureStatus === 2) {
- statementOffset++;
}
- if (constructor) {
- if (superCaptureStatus === 1) {
+ if (superCallExpression) {
hierarchyFacts |= 4096;
+ statementOffset++;
}
ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, statementOffset));
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureNewTargetIfNeeded(prologue, constructor, false);
+ if (isDerivedClass) {
+ if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 2048)) {
+ var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
+ var returnStatement = ts.createReturn(superCallExpression);
+ ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
+ ts.setEmitFlags(superCall, 1536);
+ statements.push(returnStatement);
}
- if (isDerivedClass
- && superCaptureStatus !== 2
- && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) {
+ else {
+ insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
+ if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
- if (constructor) {
- prependCaptureNewTargetIfNeeded(statements, constructor, false);
}
- var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), constructor ? constructor.body.statements : node.members), true);
- ts.setTextRange(block, constructor ? constructor.body : node);
- if (!constructor) {
- ts.setEmitFlags(block, 1536);
}
+ else {
+ insertCaptureThisForNodeIfNeeded(prologue, constructor);
+ }
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), constructor.body.statements), true);
+ ts.setTextRange(block, constructor.body);
return block;
}
function isSufficientlyCoveredByReturnStatements(statement) {
@@ -59612,49 +60593,6 @@
}
return false;
}
- function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) {
- if (!isDerivedClass) {
- if (ctor) {
- addCaptureThisForNodeIfNeeded(statements, ctor);
- }
- return 0;
- }
- if (!ctor) {
- statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
- return 2;
- }
- if (hasSynthesizedSuper) {
- captureThisForNode(statements, ctor, createDefaultSuperCallOrThis());
- enableSubstitutionsForCapturedThis();
- return 1;
- }
- var firstStatement;
- var superCallExpression;
- var ctorStatements = ctor.body.statements;
- if (statementOffset < ctorStatements.length) {
- firstStatement = ctorStatements[statementOffset];
- if (firstStatement.kind === 221 && ts.isSuperCall(firstStatement.expression)) {
- superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
- }
- }
- if (superCallExpression
- && statementOffset === ctorStatements.length - 1
- && !(ctor.transformFlags & (8192 | 16384))) {
- var returnStatement = ts.createReturn(superCallExpression);
- if (superCallExpression.kind !== 204
- || superCallExpression.left.kind !== 191) {
- ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'.");
- }
- ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536)));
- statements.push(returnStatement);
- return 2;
- }
- captureThisForNode(statements, ctor, superCallExpression || createActualThis());
- if (superCallExpression) {
- return 1;
- }
- return 0;
- }
function createActualThis() {
return ts.setEmitFlags(ts.createThis(), 4);
}
@@ -59675,13 +60613,15 @@
return node;
}
}
- function shouldAddDefaultValueAssignments(node) {
- return (node.transformFlags & 65536) !== 0;
+ function hasDefaultValueOrBindingPattern(node) {
+ return node.initializer !== undefined
+ || ts.isBindingPattern(node.name);
}
function addDefaultValueAssignmentsIfNeeded(statements, node) {
- if (!shouldAddDefaultValueAssignments(node)) {
- return;
+ if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
+ return false;
}
+ var added = false;
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
@@ -59689,23 +60629,27 @@
continue;
}
if (ts.isBindingPattern(name)) {
- addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer);
+ added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
}
else if (initializer) {
- addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
+ insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
+ added = true;
}
}
+ return added;
}
- function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
- var temp = ts.getGeneratedNameForNode(parameter);
+ function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
if (name.elements.length > 0) {
- statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, temp))), 1048576));
+ ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, ts.getGeneratedNameForNode(parameter)))), 1048576));
+ return true;
}
else if (initializer) {
- statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576));
+ ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576));
+ return true;
}
+ return false;
}
- function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
+ function insertDefaultValueAssignmentForInitializer(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.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer) | 1536)), parameter), 1536))
@@ -59713,22 +60657,23 @@
ts.startOnNewLine(statement);
ts.setTextRange(statement, parameter);
ts.setEmitFlags(statement, 384 | 32 | 1048576 | 1536);
- statements.push(statement);
+ ts.insertStatementAfterCustomPrologue(statements, statement);
}
function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper);
}
function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
+ var prologueStatements = [];
var parameter = ts.lastOrUndefined(node.parameters);
if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
- return;
+ return false;
}
var declarationName = parameter.name.kind === 72 ? ts.getMutableClone(parameter.name) : ts.createTempVariable(undefined);
ts.setEmitFlags(declarationName, 48);
var expressionName = parameter.name.kind === 72 ? ts.getSynthesizedClone(parameter.name) : declarationName;
var restIndex = node.parameters.length - 1;
var temp = ts.createLoopVariable();
- statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([
+ prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([
ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([]))
])), parameter), 1048576));
var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([
@@ -59740,27 +60685,31 @@
]));
ts.setEmitFlags(forStatement, 1048576);
ts.startOnNewLine(forStatement);
- statements.push(forStatement);
+ prologueStatements.push(forStatement);
if (parameter.name.kind !== 72) {
- statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, expressionName))), parameter), 1048576));
+ prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, expressionName))), parameter), 1048576));
}
+ ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
+ return true;
}
- function addCaptureThisForNodeIfNeeded(statements, node) {
- if (node.transformFlags & 16384 && node.kind !== 197) {
- captureThisForNode(statements, node, ts.createThis());
+ function insertCaptureThisForNodeIfNeeded(statements, node) {
+ if (hierarchyFacts & 16384 && node.kind !== 197) {
+ insertCaptureThisForNode(statements, node, ts.createThis());
+ return true;
}
+ return false;
}
- function captureThisForNode(statements, node, initializer) {
+ function insertCaptureThisForNode(statements, node, initializer) {
enableSubstitutionsForCapturedThis();
var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([
ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), undefined, initializer)
]));
ts.setEmitFlags(captureThisStatement, 1536 | 1048576);
ts.setSourceMapRange(captureThisStatement, node);
- statements.push(captureThisStatement);
+ ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
}
- function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
- if (hierarchyFacts & 16384) {
+ function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
+ if (hierarchyFacts & 8192) {
var newTarget = void 0;
switch (node.kind) {
case 197:
@@ -59783,10 +60732,11 @@
var captureNewTargetStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([
ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), undefined, newTarget)
]));
+ ts.setEmitFlags(captureNewTargetStatement, 1536 | 1048576);
if (copyOnWrite) {
- return [captureNewTargetStatement].concat(statements);
+ statements = statements.slice();
}
- statements.unshift(captureNewTargetStatement);
+ ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
}
return statements;
}
@@ -59819,7 +60769,6 @@
return ts.setTextRange(ts.createEmptyStatement(), member);
}
function transformClassMethodDeclarationToStatement(receiver, member, container) {
- var ancestorFacts = enterSubtree(0, 0);
var commentRange = ts.getCommentRange(member);
var sourceMapRange = ts.getSourceMapRange(member);
var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name);
@@ -59830,7 +60779,6 @@
ts.setOriginalNode(statement, member);
ts.setCommentRange(statement, commentRange);
ts.setEmitFlags(statement, 48);
- exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0);
return statement;
}
function transformAccessorsToStatement(receiver, accessors, container) {
@@ -59841,7 +60789,6 @@
}
function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
- var ancestorFacts = enterSubtree(0, 0);
var target = ts.getMutableClone(receiver);
ts.setEmitFlags(target, 1536 | 32);
ts.setSourceMapRange(target, firstAccessor.name);
@@ -59874,53 +60821,51 @@
if (startsOnNewLine) {
ts.startOnNewLine(call);
}
- exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0);
return call;
}
function visitArrowFunction(node) {
- if (node.transformFlags & 8192) {
- enableSubstitutionsForCapturedThis();
+ if (node.transformFlags & 2048) {
+ hierarchyFacts |= 16384;
}
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16256, 66);
+ var ancestorFacts = enterSubtree(8064, 66);
var func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node));
ts.setTextRange(func, node);
ts.setOriginalNode(func, node);
ts.setEmitFlags(func, 8);
+ if (hierarchyFacts & 16384) {
+ enableSubstitutionsForCapturedThis();
+ }
exitSubtree(ancestorFacts, 0, 0);
convertedLoopState = savedConvertedLoopState;
return func;
}
function visitFunctionExpression(node) {
var ancestorFacts = ts.getEmitFlags(node) & 262144
- ? enterSubtree(16278, 69)
- : enterSubtree(16286, 65);
+ ? enterSubtree(8086, 69)
+ : enterSubtree(8094, 65);
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & 64
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
- var name = hierarchyFacts & 16384
+ var body = transformFunctionBody(node);
+ var name = hierarchyFacts & 8192
? ts.getLocalName(node)
: node.name;
- exitSubtree(ancestorFacts, 49152, 0);
+ exitSubtree(ancestorFacts, 24576, 0);
convertedLoopState = savedConvertedLoopState;
return ts.updateFunctionExpression(node, undefined, node.asteriskToken, name, undefined, parameters, undefined, body);
}
function visitFunctionDeclaration(node) {
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16286, 65);
+ var ancestorFacts = enterSubtree(8094, 65);
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & 64
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
- var name = hierarchyFacts & 16384
+ var body = transformFunctionBody(node);
+ var name = hierarchyFacts & 8192
? ts.getLocalName(node)
: node.name;
- exitSubtree(ancestorFacts, 49152, 0);
+ exitSubtree(ancestorFacts, 24576, 0);
convertedLoopState = savedConvertedLoopState;
return ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, undefined, parameters, undefined, body);
}
@@ -59928,14 +60873,14 @@
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32)
- ? enterSubtree(16286, 65 | 8)
- : enterSubtree(16286, 65);
+ ? enterSubtree(8094, 65 | 8)
+ : enterSubtree(8094, 65);
var parameters = ts.visitParameterList(node.parameters, visitor, context);
var body = transformFunctionBody(node);
- if (hierarchyFacts & 16384 && !name && (node.kind === 239 || node.kind === 196)) {
+ if (hierarchyFacts & 8192 && !name && (node.kind === 239 || node.kind === 196)) {
name = ts.getGeneratedNameForNode(node);
}
- exitSubtree(ancestorFacts, 49152, 0);
+ exitSubtree(ancestorFacts, 24576, 0);
convertedLoopState = savedConvertedLoopState;
return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(undefined, node.asteriskToken, name, undefined, parameters, undefined, body), location), node);
}
@@ -59944,19 +60889,18 @@
var singleLine = false;
var statementsLocation;
var closeBraceLocation;
- var leadingStatements = [];
+ var prologue = [];
var statements = [];
var body = node.body;
var statementOffset;
resumeLexicalEnvironment();
if (ts.isBlock(body)) {
- statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, false);
+ statementOffset = ts.addStandardPrologue(prologue, body.statements, false);
}
- addCaptureThisForNodeIfNeeded(leadingStatements, node);
- addDefaultValueAssignmentsIfNeeded(leadingStatements, node);
- addRestParameterIfNeeded(leadingStatements, node, false);
+ multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
+ multiLine = addRestParameterIfNeeded(statements, node, false) || multiLine;
if (ts.isBlock(body)) {
- statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor);
+ statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
statementsLocation = body.statements;
ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
if (!multiLine && body.multiLine) {
@@ -59983,13 +60927,17 @@
statements.push(returnStatement);
closeBraceLocation = body;
}
- var lexicalEnvironment = context.endLexicalEnvironment();
- ts.addStatementsAfterPrologue(statements, lexicalEnvironment);
- prependCaptureNewTargetIfNeeded(statements, node, false);
- if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) {
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureNewTargetIfNeeded(prologue, node, false);
+ insertCaptureThisForNodeIfNeeded(prologue, node);
+ if (ts.some(prologue)) {
multiLine = true;
}
- var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine);
+ statements.unshift.apply(statements, prologue);
+ if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
+ return body;
+ }
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
ts.setTextRange(block, node.body);
if (!multiLine && singleLine) {
ts.setEmitFlags(block, 1);
@@ -60000,10 +60948,6 @@
ts.setOriginalNode(block, node.body);
return block;
}
- function visitFunctionBodyDownLevel(node) {
- var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context);
- return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, true)), updated.statements));
- }
function visitBlock(node, isFunctionBody) {
if (isFunctionBody) {
return ts.visitEachChild(node, visitor, context);
@@ -60075,7 +61019,7 @@
return updated;
}
function visitVariableDeclarationList(node) {
- if (node.transformFlags & 64) {
+ if (node.flags & 3 || node.transformFlags & 65536) {
if (node.flags & 3) {
enableSubstitutionsForBlockScopedBindings();
}
@@ -60086,7 +61030,7 @@
ts.setOriginalNode(declarationList, node);
ts.setTextRange(declarationList, node);
ts.setCommentRange(declarationList, node);
- if (node.transformFlags & 2097152
+ if (node.transformFlags & 65536
&& (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
}
@@ -60287,7 +61231,7 @@
var numInitialPropertiesWithoutYield = numProperties;
for (var i = 0; i < numProperties; i++) {
var property = properties[i];
- if ((property.transformFlags & 4194304 && hierarchyFacts & 4)
+ if ((property.transformFlags & 131072 && hierarchyFacts & 4)
&& i < numInitialPropertiesWithoutYield) {
numInitialPropertiesWithoutYield = i;
}
@@ -60518,7 +61462,7 @@
}
function createFunctionForInitializerOfForStatement(node, currentState) {
var functionName = ts.createUniqueName("_loop_init");
- var containsYield = (node.initializer.transformFlags & 4194304) !== 0;
+ var containsYield = (node.initializer.transformFlags & 131072) !== 0;
var emitFlags = 0;
if (currentState.containsLexicalThis)
emitFlags |= 8;
@@ -60553,11 +61497,11 @@
statements.push(statement);
}
copyOutParameters(currentState.loopOutParameters, 1, 1, statements);
- ts.addStatementsAfterPrologue(statements, lexicalEnvironment);
+ ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
var loopBody = ts.createBlock(statements, true);
if (ts.isBlock(statement))
ts.setOriginalNode(loopBody, statement);
- var containsYield = (node.statement.transformFlags & 4194304) !== 0;
+ var containsYield = (node.statement.transformFlags & 131072) !== 0;
var emitFlags = 0;
if (currentState.containsLexicalThis)
emitFlags |= 8;
@@ -60732,13 +61676,11 @@
return expression;
}
function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
- var ancestorFacts = enterSubtree(0, 0);
var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, method, undefined, container));
ts.setTextRange(expression, method);
if (startsOnNewLine) {
ts.startOnNewLine(expression);
}
- exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0);
return expression;
}
function visitCatchClause(node) {
@@ -60775,19 +61717,17 @@
ts.Debug.assert(!ts.isComputedPropertyName(node.name));
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16286, 65);
+ var ancestorFacts = enterSubtree(8094, 65);
var updated;
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & (16384 | 128)
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
+ var body = transformFunctionBody(node);
if (node.kind === 158) {
updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
}
else {
updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
}
- exitSubtree(ancestorFacts, 49152, 0);
+ exitSubtree(ancestorFacts, 24576, 0);
convertedLoopState = savedConvertedLoopState;
return updated;
}
@@ -60795,16 +61735,13 @@
return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), node);
}
function visitComputedPropertyName(node) {
- var ancestorFacts = enterSubtree(0, 8192);
- var updated = ts.visitEachChild(node, visitor, context);
- exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 32768 : 0);
- return updated;
+ return ts.visitEachChild(node, visitor, context);
}
function visitYieldExpression(node) {
return ts.visitEachChild(node, visitor, context);
}
function visitArrayLiteralExpression(node) {
- if (node.transformFlags & 64) {
+ if (ts.some(node.elements, ts.isSpreadElement)) {
return transformAndSpreadElements(node.elements, true, !!node.multiLine, !!node.elements.hasTrailingComma);
}
return ts.visitEachChild(node, visitor, context);
@@ -60813,7 +61750,10 @@
if (ts.getEmitFlags(node) & 33554432) {
return visitTypeScriptClassWrapper(node);
}
- if (node.transformFlags & 64) {
+ var expression = ts.skipOuterExpressions(node.expression);
+ if (expression.kind === 98 ||
+ ts.isSuperProperty(expression) ||
+ ts.some(node.arguments, ts.isSpreadElement)) {
return visitCallExpressionWithPotentialCapturedThisAssignment(node, true);
}
return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
@@ -60859,7 +61799,7 @@
return visitCallExpressionWithPotentialCapturedThisAssignment(node, false);
}
function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
- if (node.transformFlags & 131072 ||
+ if (node.transformFlags & 4096 ||
node.expression.kind === 98 ||
ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
@@ -60867,16 +61807,14 @@
ts.setEmitFlags(thisArg, 4);
}
var resultingCall = void 0;
- if (node.transformFlags & 131072) {
- resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false));
+ if (node.transformFlags & 4096) {
+ resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false));
}
else {
- resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node);
+ resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node);
}
if (node.expression.kind === 98) {
- var actualThis = ts.createThis();
- ts.setEmitFlags(actualThis, 4);
- var initializer = ts.createLogicalOr(resultingCall, actualThis);
+ var initializer = ts.createLogicalOr(resultingCall, createActualThis());
resultingCall = assignToCapturedThis
? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
: initializer;
@@ -60886,7 +61824,7 @@
return ts.visitEachChild(node, visitor, context);
}
function visitNewExpression(node) {
- if (node.transformFlags & 131072) {
+ if (ts.some(node.arguments, ts.isSpreadElement)) {
var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), false, false, false)), undefined, []);
}
@@ -61027,19 +61965,14 @@
}
function visitMetaProperty(node) {
if (node.keywordToken === 95 && node.name.escapedText === "target") {
- if (hierarchyFacts & 8192) {
- hierarchyFacts |= 32768;
- }
- else {
- hierarchyFacts |= 16384;
- }
+ hierarchyFacts |= 8192;
return ts.createFileLevelUniqueName("_newTarget");
}
return node;
}
function onEmitNode(hint, node, emitCallback) {
if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) {
- var ancestorFacts = enterSubtree(16286, ts.getEmitFlags(node) & 8
+ var ancestorFacts = enterSubtree(8094, ts.getEmitFlags(node) & 8
? 65 | 16
: 65);
previousOnEmitNode(hint, node, emitCallback);
@@ -61173,26 +62106,26 @@
}
ts.transformES2015 = transformES2015;
function createExtendsHelper(context, name) {
- context.requestEmitHelper(extendsHelper);
+ context.requestEmitHelper(ts.extendsHelper);
return ts.createCall(ts.getHelperName("__extends"), undefined, [
name,
ts.createFileLevelUniqueName("_super")
]);
}
function createTemplateObjectHelper(context, cooked, raw) {
- context.requestEmitHelper(templateObjectHelper);
+ context.requestEmitHelper(ts.templateObjectHelper);
return ts.createCall(ts.getHelperName("__makeTemplateObject"), undefined, [
cooked,
raw
]);
}
- var extendsHelper = {
+ ts.extendsHelper = {
name: "typescript:extends",
scoped: false,
priority: 0,
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 = {
+ ts.templateObjectHelper = {
name: "typescript:makeTemplateObject",
scoped: false,
priority: 0,
@@ -61315,7 +62248,7 @@
var withBlockStack;
return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
- if (node.isDeclarationFile || (node.transformFlags & 512) === 0) {
+ if (node.isDeclarationFile || (node.transformFlags & 256) === 0) {
return node;
}
var visited = ts.visitEachChild(node, visitor, context);
@@ -61330,10 +62263,10 @@
else if (inGeneratorFunctionBody) {
return visitJavaScriptInGeneratorFunctionBody(node);
}
- else if (transformFlags & 256) {
+ else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
return visitGenerator(node);
}
- else if (transformFlags & 512) {
+ else if (transformFlags & 256) {
return ts.visitEachChild(node, visitor, context);
}
else {
@@ -61376,10 +62309,10 @@
case 230:
return visitReturnStatement(node);
default:
- if (node.transformFlags & 4194304) {
+ if (node.transformFlags & 131072) {
return visitJavaScriptContainingYield(node);
}
- else if (node.transformFlags & (512 | 8388608)) {
+ else if (node.transformFlags & (256 | 262144)) {
return ts.visitEachChild(node, visitor, context);
}
else {
@@ -61497,7 +62430,7 @@
var statementOffset = ts.addPrologue(statements, body.statements, false, visitor);
transformAndEmitStatements(body.statements, statementOffset);
var buildResult = build();
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
statements.push(ts.createReturn(buildResult));
inGeneratorFunctionBody = savedInGeneratorFunctionBody;
inStatementContainingYield = savedInStatementContainingYield;
@@ -61515,7 +62448,7 @@
return ts.setTextRange(ts.createBlock(statements, body.multiLine), body);
}
function visitVariableStatement(node) {
- if (node.transformFlags & 4194304) {
+ if (node.transformFlags & 131072) {
transformAndEmitVariableDeclarationList(node.declarationList);
return undefined;
}
@@ -62196,7 +63129,7 @@
}
}
function containsYield(node) {
- return !!node && (node.transformFlags & 4194304) !== 0;
+ return !!node && (node.transformFlags & 131072) !== 0;
}
function countInitialNodesWithoutYield(nodes) {
var numNodes = nodes.length;
@@ -62891,10 +63824,10 @@
}
ts.transformGenerators = transformGenerators;
function createGeneratorHelper(context, body) {
- context.requestEmitHelper(generatorHelper);
+ context.requestEmitHelper(ts.generatorHelper);
return ts.createCall(ts.getHelperName("__generator"), undefined, [ts.createThis(), body]);
}
- var generatorHelper = {
+ ts.generatorHelper = {
name: "typescript:generator",
scoped: false,
priority: 6,
@@ -62926,7 +63859,7 @@
context.enableSubstitution(202);
context.enableSubstitution(203);
context.enableSubstitution(276);
- context.enableEmitNotification(279);
+ context.enableEmitNotification(284);
var moduleInfoMap = [];
var deferredExports = [];
var currentSourceFile;
@@ -62937,7 +63870,7 @@
function transformSourceFile(node) {
if (node.isDeclarationFile ||
!(ts.isEffectiveExternalModule(node, compilerOptions) ||
- node.transformFlags & 16777216 ||
+ node.transformFlags & 524288 ||
(ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
return node;
}
@@ -62968,7 +63901,7 @@
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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
ts.addEmitHelper(updated, exportStarHelper);
@@ -63086,7 +64019,7 @@
}
ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
addExportEqualsIfNeeded(statements, true);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var body = ts.createBlock(statements, true);
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
ts.addEmitHelper(body, exportStarHelper);
@@ -63131,22 +64064,22 @@
return visitFunctionDeclaration(node);
case 240:
return visitClassDeclaration(node);
- case 310:
+ case 315:
return visitMergeDeclarationMarker(node);
- case 311:
+ case 316:
return visitEndOfDeclarationMarker(node);
default:
return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
}
}
function moduleExpressionElementVisitor(node) {
- if (!(node.transformFlags & 16777216) && !(node.transformFlags & 2048)) {
+ if (!(node.transformFlags & 524288) && !(node.transformFlags & 512)) {
return node;
}
if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
- else if (node.transformFlags & 1024 && ts.isBinaryExpression(node)) {
+ else if (ts.isDestructuringAssignment(node)) {
return visitDestructuringAssignment(node);
}
else {
@@ -63207,7 +64140,7 @@
}
function visitImportCallExpression(node) {
var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
- var containsLexicalThis = !!(node.transformFlags & 8192);
+ var containsLexicalThis = !!(node.transformFlags & 2048);
switch (compilerOptions.module) {
case ts.ModuleKind.AMD:
return createImportCallExpressionAMD(argument, containsLexicalThis);
@@ -63251,7 +64184,7 @@
}
var promise = ts.createNew(ts.createIdentifier("Promise"), undefined, [func]);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), undefined, [ts.getHelperName("__importStar")]);
}
return promise;
@@ -63260,7 +64193,7 @@
var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []);
var requireCall = ts.createCall(ts.createIdentifier("require"), undefined, arg ? [arg] : []);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
requireCall = ts.createCall(ts.getHelperName("__importStar"), undefined, [requireCall]);
}
var func;
@@ -63280,11 +64213,11 @@
return innerExpr;
}
if (ts.getImportNeedsImportStarHelper(node)) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.getHelperName("__importStar"), undefined, [innerExpr]);
}
if (ts.getImportNeedsImportDefaultHelper(node)) {
- context.requestEmitHelper(importDefaultHelper);
+ context.requestEmitHelper(ts.importDefaultHelper);
return ts.createCall(ts.getHelperName("__importDefault"), undefined, [innerExpr]);
}
return innerExpr;
@@ -63633,7 +64566,7 @@
return node;
}
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279) {
+ if (node.kind === 284) {
currentSourceFile = node;
currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
noSubstitution = [];
@@ -63693,7 +64626,7 @@
}
if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
- if (exportContainer && exportContainer.kind === 279) {
+ if (exportContainer && exportContainer.kind === 284) {
return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), node);
}
var importDeclaration = resolver.getReferencedImportDeclaration(node);
@@ -63777,12 +64710,12 @@
scoped: true,
text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
};
- var importStarHelper = {
+ ts.importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
- var importDefaultHelper = {
+ ts.importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
@@ -63804,7 +64737,7 @@
context.enableSubstitution(204);
context.enableSubstitution(202);
context.enableSubstitution(203);
- context.enableEmitNotification(279);
+ context.enableEmitNotification(284);
var moduleInfoMap = [];
var deferredExports = [];
var exportFunctionsMap = [];
@@ -63818,7 +64751,7 @@
var noSubstitution;
return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
- if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216)) {
+ if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 524288)) {
return node;
}
var id = ts.getOriginalNodeId(node);
@@ -63890,7 +64823,7 @@
ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement);
var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset);
ts.addRange(statements, hoistedStatements);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var exportStarFunction = addExportStarIfNeeded(statements);
var moduleObject = ts.createObjectLiteral([
ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
@@ -64139,7 +65072,7 @@
}
function shouldHoistVariableDeclarationList(node) {
return (ts.getEmitFlags(node) & 2097152) === 0
- && (enclosingBlockScopedContainer.kind === 279
+ && (enclosingBlockScopedContainer.kind === 284
|| (ts.getOriginalNode(node).flags & 3) === 0);
}
function transformInitializedVariable(node, isExportedDeclaration) {
@@ -64337,9 +65270,9 @@
return visitCatchClause(node);
case 218:
return visitBlock(node);
- case 310:
+ case 315:
return visitMergeDeclarationMarker(node);
- case 311:
+ case 316:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -64432,14 +65365,13 @@
return node;
}
function destructuringAndImportCallVisitor(node) {
- if (node.transformFlags & 1024
- && node.kind === 204) {
+ if (ts.isDestructuringAssignment(node)) {
return visitDestructuringAssignment(node);
}
else if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
- else if ((node.transformFlags & 2048) || (node.transformFlags & 16777216)) {
+ else if ((node.transformFlags & 512) || (node.transformFlags & 524288)) {
return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
}
else {
@@ -64476,7 +65408,7 @@
}
else if (ts.isIdentifier(node)) {
var container = resolver.getReferencedExportContainer(node);
- return container !== undefined && container.kind === 279;
+ return container !== undefined && container.kind === 284;
}
else {
return false;
@@ -64491,7 +65423,7 @@
return node;
}
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279) {
+ if (node.kind === 284) {
var id = ts.getOriginalNodeId(node);
currentSourceFile = node;
moduleInfo = moduleInfoMap[id];
@@ -64628,7 +65560,7 @@
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
var exportContainer = resolver.getReferencedExportContainer(name, false);
- if (exportContainer && exportContainer.kind === 279) {
+ if (exportContainer && exportContainer.kind === 284) {
exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
}
exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
@@ -64656,7 +65588,7 @@
var previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- context.enableEmitNotification(279);
+ context.enableEmitNotification(284);
context.enableSubstitution(72);
var currentSourceFile;
return ts.chainBundle(transformSourceFile);
@@ -64742,7 +65674,8 @@
ts.isImportEqualsDeclaration(node) ||
ts.isTypeAliasDeclaration(node) ||
ts.isConstructorDeclaration(node) ||
- ts.isIndexSignatureDeclaration(node);
+ ts.isIndexSignatureDeclaration(node) ||
+ ts.isPropertyAccessExpression(node);
}
ts.canProduceDiagnostics = canProduceDiagnostics;
function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
@@ -64816,7 +65749,7 @@
}
ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
function createGetSymbolAccessibilityDiagnosticForNode(node) {
- if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
+ if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
return getVariableDeclarationTypeVisibilityError;
}
else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
@@ -64854,7 +65787,7 @@
ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
}
- else if (node.kind === 154 || node.kind === 153 ||
+ else if (node.kind === 154 || node.kind === 189 || node.kind === 153 ||
(node.kind === 151 && ts.hasModifier(node.parent, 8))) {
if (ts.hasModifier(node, 32)) {
return symbolAccessibilityResult.errorModuleName ?
@@ -65046,6 +65979,9 @@
case 241:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
break;
+ case 181:
+ diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
+ break;
case 166:
case 161:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
@@ -65125,6 +66061,27 @@
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
+ function hasInternalAnnotation(range, currentSourceFile) {
+ var comment = currentSourceFile.text.substring(range.pos, range.end);
+ return ts.stringContains(comment, "@internal");
+ }
+ function isInternalDeclaration(node, currentSourceFile) {
+ var parseTreeNode = ts.getParseTreeNode(node);
+ if (parseTreeNode && parseTreeNode.kind === 151) {
+ var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
+ var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
+ var text = currentSourceFile.text;
+ var commentRanges = previousSibling
+ ? ts.concatenate(ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, false, true)), ts.getLeadingCommentRanges(text, node.pos))
+ : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, false, true));
+ return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
+ }
+ var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
+ return !!ts.forEach(leadingCommentRanges, function (range) {
+ return hasInternalAnnotation(range, currentSourceFile);
+ });
+ }
+ ts.isInternalDeclaration = isInternalDeclaration;
var declarationEmitNodeBuilderFlags = 1024 |
2048 |
4096 |
@@ -65242,10 +66199,10 @@
}
}
function transformRoot(node) {
- if (node.kind === 279 && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
+ if (node.kind === 284 && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
}
- if (node.kind === 280) {
+ if (node.kind === 285) {
isBundledEmit = true;
refs = ts.createMap();
libs = ts.createMap();
@@ -65275,9 +66232,15 @@
var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), true, [], [], false, []);
}), ts.mapDefined(node.prepends, function (prepend) {
- if (prepend.kind === 282) {
- return ts.createUnparsedSourceFile(prepend, "dts");
+ if (prepend.kind === 287) {
+ var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
+ hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
+ collectReferences(sourceFile, refs);
+ recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
+ collectLibs(sourceFile, libs);
+ return sourceFile;
}
+ return prepend;
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -65364,7 +66327,7 @@
}
}
function collectReferences(sourceFile, ret) {
- if (noResolve || ts.isSourceFileJS(sourceFile))
+ if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
return ret;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
@@ -65850,7 +66813,9 @@
if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
return undefined;
}
+ getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker);
+ getSymbolAccessibilityDiagnostic = oldDiag;
var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, undefined);
return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([varDecl]));
});
@@ -65890,7 +66855,7 @@
if (ctor) {
var oldDiag_1 = getSymbolAccessibilityDiagnostic;
parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
- if (!ts.hasModifier(param, 92))
+ if (!ts.hasModifier(param, 92) || shouldStripInternal(param))
return;
getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
if (param.name.kind === 72) {
@@ -66016,18 +66981,8 @@
}
errorNameNode = undefined;
}
- function hasInternalAnnotation(range) {
- var comment = currentSourceFile.text.substring(range.pos, range.end);
- return ts.stringContains(comment, "@internal");
- }
function shouldStripInternal(node) {
- if (stripInternal && node) {
- var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile);
- if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
- return true;
- }
- }
- return false;
+ return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
}
function isScopeMarker(node) {
return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
@@ -66049,7 +67004,7 @@
function ensureModifierFlags(node, privateDeclaration) {
var mask = 3071 ^ (4 | 256);
var additions = (needsDeclare && !isAlwaysType(node)) ? 2 : 0;
- var parentIsFile = node.parent.kind === 279;
+ var parentIsFile = node.parent.kind === 284;
if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1) | 2);
additions = 0;
@@ -66201,9 +67156,15 @@
if (jsx === 2) {
transformers.push(ts.transformJsx);
}
- if (languageVersion < 6) {
+ if (languageVersion < 7) {
transformers.push(ts.transformESNext);
}
+ if (languageVersion < 6) {
+ transformers.push(ts.transformES2019);
+ }
+ if (languageVersion < 5) {
+ transformers.push(ts.transformES2018);
+ }
if (languageVersion < 4) {
transformers.push(ts.transformES2017);
}
@@ -66231,7 +67192,7 @@
}
ts.noEmitNotification = noEmitNotification;
function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
- var enabledSyntaxKindFeatures = new Array(312);
+ var enabledSyntaxKindFeatures = new Array(317);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -66432,16 +67393,20 @@
})(ts || (ts = {}));
var ts;
(function (ts) {
- var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
var syntheticParent = { pos: -1, end: -1 };
- function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
+ function isBuildInfoFile(file) {
+ return ts.fileExtensionIs(file, ".tsbuildinfo");
+ }
+ ts.isBuildInfoFile = isBuildInfoFile;
+ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles, onlyBuildInfo, includeBuildInfo) {
if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; }
var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
+ var prepends = host.getPrependNodes();
+ if (sourceFiles.length || prepends.length) {
+ var bundle = ts.createBundle(sourceFiles, prepends);
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -66449,6 +67414,7 @@
}
}
else {
+ if (!onlyBuildInfo) {
for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
var sourceFile = sourceFiles_1[_a];
var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
@@ -66457,21 +67423,49 @@
}
}
}
+ if (includeBuildInfo) {
+ var buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
+ if (buildInfoPath)
+ return action({ buildInfoPath: buildInfoPath }, undefined);
+ }
+ }
}
ts.forEachEmittedFile = forEachEmittedFile;
+ function getOutputPathForBuildInfo(options) {
+ var configFile = options.configFilePath;
+ if (!configFile || !ts.isIncrementalCompilation(options))
+ return undefined;
+ if (options.tsBuildInfoFile)
+ return options.tsBuildInfoFile;
+ var outPath = options.outFile || options.out;
+ var buildInfoExtensionLess;
+ if (outPath) {
+ buildInfoExtensionLess = ts.removeFileExtension(outPath);
+ }
+ else {
+ var configFileExtensionLess = ts.removeFileExtension(configFile);
+ buildInfoExtensionLess = options.outDir ?
+ options.rootDir ?
+ ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, true)) :
+ ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
+ configFileExtensionLess;
+ }
+ return buildInfoExtensionLess + ".tsbuildinfo";
+ }
+ ts.getOutputPathForBuildInfo = getOutputPathForBuildInfo;
function getOutputPathsForBundle(options, forceDtsPaths) {
var outPath = options.outFile || options.out;
var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" : undefined;
var declarationMapPath = declarationFilePath && 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 };
+ var buildInfoPath = getOutputPathForBuildInfo(options);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
}
ts.getOutputPathsForBundle = getOutputPathsForBundle;
function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
var options = host.getCompilerOptions();
- if (sourceFile.kind === 280) {
+ if (sourceFile.kind === 285) {
return getOutputPathsForBundle(options, forceDtsPaths);
}
else {
@@ -66483,19 +67477,13 @@
var isJs = ts.isSourceFileJS(sourceFile);
var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
}
}
ts.getOutputPathsFor = getOutputPathsFor;
function getSourceMapFilePath(jsFilePath, options) {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
- function createDefaultBundleInfo() {
- return {
- originalOffset: -1,
- totalLength: -1
- };
- }
function getOutputExtension(sourceFile, options) {
if (ts.isJsonSourceFile(sourceFile)) {
return ".json";
@@ -66513,7 +67501,86 @@
return ".js";
}
ts.getOutputExtension = getOutputExtension;
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
+ function rootDirOfOptions(configFile) {
+ return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.assertDefined(configFile.options.configFilePath));
+ }
+ function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
+ return outputDir ?
+ ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
+ inputFileName;
+ }
+ function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
+ ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts") && ts.hasTSFileExtension(inputFileName));
+ return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts");
+ }
+ ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
+ function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
+ var isJsonFile = ts.fileExtensionIs(inputFileName, ".json");
+ var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
+ ".json" :
+ ts.fileExtensionIs(inputFileName, ".tsx") && configFile.options.jsx === 1 ?
+ ".jsx" :
+ ".js");
+ return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.assertDefined(configFile.options.configFilePath), ignoreCase) !== 0 ?
+ outputFileName :
+ undefined;
+ }
+ function getAllProjectOutputs(configFile, ignoreCase) {
+ var outputs;
+ var addOutput = function (path) { return path && (outputs || (outputs = [])).push(path); };
+ if (configFile.options.outFile || configFile.options.out) {
+ var _a = getOutputPathsForBundle(configFile.options, false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ addOutput(jsFilePath);
+ addOutput(sourceMapFilePath);
+ addOutput(declarationFilePath);
+ addOutput(declarationMapPath);
+ addOutput(buildInfoPath);
+ }
+ else {
+ for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
+ var inputFileName = _c[_b];
+ if (ts.fileExtensionIs(inputFileName, ".d.ts"))
+ continue;
+ var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ addOutput(js);
+ if (ts.fileExtensionIs(inputFileName, ".json"))
+ continue;
+ if (configFile.options.sourceMap) {
+ addOutput(js + ".map");
+ }
+ if (ts.getEmitDeclarations(configFile.options) && ts.hasTSFileExtension(inputFileName)) {
+ var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
+ addOutput(dts);
+ if (configFile.options.declarationMap) {
+ addOutput(dts + ".map");
+ }
+ }
+ }
+ addOutput(getOutputPathForBuildInfo(configFile.options));
+ }
+ return outputs || ts.emptyArray;
+ }
+ ts.getAllProjectOutputs = getAllProjectOutputs;
+ function getFirstProjectOutput(configFile, ignoreCase) {
+ if (configFile.options.outFile || configFile.options.out) {
+ var jsFilePath = getOutputPathsForBundle(configFile.options, false).jsFilePath;
+ return ts.Debug.assertDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
+ }
+ for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
+ var inputFileName = _b[_a];
+ if (ts.fileExtensionIs(inputFileName, ".d.ts"))
+ continue;
+ var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ if (jsFilePath)
+ return jsFilePath;
+ }
+ var buildInfoPath = getOutputPathForBuildInfo(configFile.options);
+ if (buildInfoPath)
+ return buildInfoPath;
+ return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
+ }
+ ts.getFirstProjectOutput = getFirstProjectOutput;
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers, onlyBuildInfo) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -66521,11 +67588,11 @@
var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
var writer = ts.createTextWriter(newLine);
var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit;
- var bundleInfo = createDefaultBundleInfo();
+ var bundleBuildInfo;
var emitSkipped = false;
var exportedModulesFromDeclarationEmit;
enter();
- forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles);
+ forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile);
exit();
return {
emitSkipped: emitSkipped,
@@ -66535,9 +67602,16 @@
exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
+ bundleBuildInfo = {
+ commonSourceDirectory: host.getCommonSourceDirectory(),
+ sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return file.fileName; })
+ };
+ }
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
+ emitBuildInfo(bundleBuildInfo, buildInfoPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
if (jsFilePath) {
@@ -66546,8 +67620,8 @@
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
- if (bundleInfoPath) {
- emittedFilesList.push(bundleInfoPath);
+ if (buildInfoPath) {
+ emittedFilesList.push(buildInfoPath);
}
}
if (declarationFilePath) {
@@ -66558,8 +67632,20 @@
}
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
- if (emitOnlyDtsFiles || !jsFilePath) {
+ function emitBuildInfo(bundle, buildInfoPath) {
+ if (!buildInfoPath || targetSourceFile || emitSkipped)
+ return;
+ var program = host.getProgramBuildInfo();
+ if (!bundle && !program)
+ return;
+ if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
+ emitSkipped = true;
+ return;
+ }
+ ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: ts.version }), false);
+ }
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
+ if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
return;
}
if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
@@ -66577,6 +67663,7 @@
inlineSourceMap: compilerOptions.inlineSourceMap,
inlineSources: compilerOptions.inlineSources,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ writeBundleFileInfo: !!bundleBuildInfo
};
var printer = createPrinter(printerOptions, {
hasGlobalName: resolver.hasGlobalName,
@@ -66584,11 +67671,13 @@
substituteNode: transform.substituteNode,
});
ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions);
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
transform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.js = printer.bundleFileInfo;
}
function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) {
- if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
+ if (!sourceFileOrBundle || !(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
return;
}
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
@@ -66614,6 +67703,8 @@
inlineSourceMap: compilerOptions.inlineSourceMap,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
onlyPrintJsDocStyle: true,
+ writeBundleFileInfo: !!bundleBuildInfo,
+ recordInternalSection: !!bundleBuildInfo
};
var declarationPrinter = createPrinter(printerOptions, {
hasGlobalName: resolver.hasGlobalName,
@@ -66624,18 +67715,20 @@
emitSkipped = emitSkipped || declBlocked;
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, {
+ printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
sourceMap: compilerOptions.declarationMap,
sourceRoot: compilerOptions.sourceRoot,
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
- if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279) {
+ if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 284) {
var sourceFile = declarationTransform.transformed[0];
exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
}
}
declarationTransform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
}
function collectLinkedAliases(node) {
if (ts.isExportAssignment(node)) {
@@ -66650,16 +67743,16 @@
}
ts.forEachChild(node, collectLinkedAliases);
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) {
- var bundle = sourceFileOrBundle.kind === 280 ? sourceFileOrBundle : undefined;
- var sourceFile = sourceFileOrBundle.kind === 279 ? sourceFileOrBundle : undefined;
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
+ var bundle = sourceFileOrBundle.kind === 285 ? sourceFileOrBundle : undefined;
+ var sourceFile = sourceFileOrBundle.kind === 284 ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
var sourceMapGenerator;
if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
}
if (bundle) {
- printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator);
+ printer.writeBundle(bundle, writer, sourceMapGenerator);
}
else {
printer.writeFile(sourceFile, writer, sourceMapGenerator);
@@ -66686,16 +67779,11 @@
writer.writeLine();
}
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
- if (bundleInfoPath) {
- bundleInfo.totalLength = writer.getTextPos();
- ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), false);
- }
writer.clear();
- bundleInfo = createDefaultBundleInfo();
}
function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
- && (sourceFileOrBundle.kind !== 279 || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json"));
+ && (sourceFileOrBundle.kind !== 284 || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json"));
}
function getSourceRoot(mapOptions) {
var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || "");
@@ -66740,6 +67828,157 @@
}
}
ts.emitFiles = emitFiles;
+ function getBuildInfoText(buildInfo) {
+ return JSON.stringify(buildInfo, undefined, 2);
+ }
+ ts.getBuildInfoText = getBuildInfoText;
+ function getBuildInfo(buildInfoText) {
+ return JSON.parse(buildInfoText);
+ }
+ ts.getBuildInfo = getBuildInfo;
+ ts.notImplementedResolver = {
+ hasGlobalName: ts.notImplemented,
+ getReferencedExportContainer: ts.notImplemented,
+ getReferencedImportDeclaration: ts.notImplemented,
+ getReferencedDeclarationWithCollidingName: ts.notImplemented,
+ isDeclarationWithCollidingName: ts.notImplemented,
+ isValueAliasDeclaration: ts.notImplemented,
+ isReferencedAliasDeclaration: ts.notImplemented,
+ isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
+ getNodeCheckFlags: ts.notImplemented,
+ isDeclarationVisible: ts.notImplemented,
+ isLateBound: function (_node) { return false; },
+ collectLinkedAliases: ts.notImplemented,
+ isImplementationOfOverload: ts.notImplemented,
+ isRequiredInitializedParameter: ts.notImplemented,
+ isOptionalUninitializedParameterProperty: ts.notImplemented,
+ isExpandoFunctionDeclaration: ts.notImplemented,
+ getPropertiesOfContainerFunction: ts.notImplemented,
+ createTypeOfDeclaration: ts.notImplemented,
+ createReturnTypeOfSignatureDeclaration: ts.notImplemented,
+ createTypeOfExpression: ts.notImplemented,
+ createLiteralConstValue: ts.notImplemented,
+ isSymbolAccessible: ts.notImplemented,
+ isEntityNameVisible: ts.notImplemented,
+ getConstantValue: ts.notImplemented,
+ getReferencedValueDeclaration: ts.notImplemented,
+ getTypeReferenceSerializationKind: ts.notImplemented,
+ isOptionalParameter: ts.notImplemented,
+ moduleExportsSomeValue: ts.notImplemented,
+ isArgumentsLocalBinding: ts.notImplemented,
+ getExternalModuleFileFromDeclaration: ts.notImplemented,
+ getTypeReferenceDirectivesForEntityName: ts.notImplemented,
+ getTypeReferenceDirectivesForSymbol: ts.notImplemented,
+ isLiteralConstDeclaration: ts.notImplemented,
+ getJsxFactoryEntity: ts.notImplemented,
+ getAllAccessorDeclarations: ts.notImplemented,
+ getSymbolOfExternalModuleSpecifier: ts.notImplemented,
+ isBindingCapturedByNode: ts.notImplemented,
+ };
+ function createSourceFilesFromBundleBuildInfo(bundle) {
+ var sourceFiles = bundle.sourceFiles.map(function (fileName) {
+ var sourceFile = ts.createNode(284, 0, 0);
+ sourceFile.fileName = fileName;
+ sourceFile.text = "";
+ sourceFile.statements = ts.createNodeArray();
+ return sourceFile;
+ });
+ var jsBundle = ts.Debug.assertDefined(bundle.js);
+ ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
+ var sourceFile = sourceFiles[prologueInfo.file];
+ sourceFile.text = prologueInfo.text;
+ sourceFile.end = prologueInfo.text.length;
+ sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
+ var statement = ts.createNode(221, directive.pos, directive.end);
+ statement.expression = ts.createNode(10, directive.expression.pos, directive.expression.end);
+ statement.expression.text = directive.expression.text;
+ return statement;
+ }));
+ });
+ return sourceFiles;
+ }
+ function emitUsingBuildInfo(config, host, getCommandLine) {
+ var _a = getOutputPathsForBundle(config.options, false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
+ var buildInfoText = host.readFile(ts.Debug.assertDefined(buildInfoPath));
+ if (!buildInfoText)
+ return buildInfoPath;
+ var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath));
+ if (!jsFileText)
+ return jsFilePath;
+ var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
+ if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
+ return sourceMapFilePath || "inline sourcemap decoding";
+ var declarationText = declarationFilePath && host.readFile(declarationFilePath);
+ if (declarationFilePath && !declarationText)
+ return declarationFilePath;
+ var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
+ if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
+ return declarationMapPath || "inline sourcemap decoding";
+ var buildInfo = getBuildInfo(buildInfoText);
+ if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
+ return buildInfoPath;
+ var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, true);
+ var outputFiles = [];
+ var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
+ var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle);
+ var emitHost = {
+ getPrependNodes: ts.memoize(function () { return prependNodes.concat([ownPrependInput]); }),
+ getCanonicalFileName: host.getCanonicalFileName,
+ getCommonSourceDirectory: function () { return buildInfo.bundle.commonSourceDirectory; },
+ getCompilerOptions: function () { return config.options; },
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ getNewLine: function () { return host.getNewLine(); },
+ getSourceFile: ts.returnUndefined,
+ getSourceFileByPath: ts.returnUndefined,
+ getSourceFiles: function () { return sourceFilesForJsEmit; },
+ getLibFileFromReference: ts.notImplemented,
+ isSourceFileFromExternalLibrary: ts.returnFalse,
+ getResolvedProjectReferenceToRedirect: ts.returnUndefined,
+ writeFile: function (name, text, writeByteOrderMark) {
+ switch (name) {
+ case jsFilePath:
+ if (jsFileText === text)
+ return;
+ break;
+ case sourceMapFilePath:
+ if (sourceMapText === text)
+ return;
+ break;
+ case buildInfoPath:
+ var newBuildInfo = getBuildInfo(text);
+ newBuildInfo.program = buildInfo.program;
+ var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
+ newBuildInfo.bundle.js.sources = js.sources;
+ if (dts) {
+ newBuildInfo.bundle.dts.sources = dts.sources;
+ }
+ newBuildInfo.bundle.sourceFiles = sourceFiles;
+ outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
+ return;
+ case declarationFilePath:
+ if (declarationText === text)
+ return;
+ break;
+ case declarationMapPath:
+ if (declarationMapText === text)
+ return;
+ break;
+ default:
+ ts.Debug.fail("Unexpected path: " + name);
+ }
+ outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
+ },
+ isEmitBlocked: ts.returnFalse,
+ readFile: function (f) { return host.readFile(f); },
+ fileExists: function (f) { return host.fileExists(f); },
+ directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }),
+ useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
+ getProgramBuildInfo: ts.returnUndefined
+ };
+ emitFiles(ts.notImplementedResolver, emitHost, undefined, false, ts.getTransformers(config.options));
+ return outputFiles;
+ }
+ ts.emitUsingBuildInfo = emitUsingBuildInfo;
function createPrinter(printerOptions, handlers) {
if (printerOptions === void 0) { printerOptions = {}; }
if (handlers === void 0) { handlers = {}; }
@@ -66760,6 +67999,10 @@
var ownWriter;
var write = writeBase;
var isOwnFileEmit;
+ var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
+ var recordInternalSection = printerOptions.recordInternalSection;
+ var sourceFileTextPos = 0;
+ var sourceFileTextKind = "text";
var sourceMapsDisabled = true;
var sourceMapGenerator;
var sourceMapSource;
@@ -66781,7 +68024,8 @@
writeNode: writeNode,
writeList: writeList,
writeFile: writeFile,
- writeBundle: writeBundle
+ writeBundle: writeBundle,
+ bundleFileInfo: bundleFileInfo
};
function printNode(hint, node, sourceFile) {
switch (hint) {
@@ -66796,9 +68040,9 @@
break;
}
switch (node.kind) {
- case 279: return printFile(node);
- case 280: return printBundle(node);
- case 281: return printUnparsedSource(node);
+ case 284: return printFile(node);
+ case 285: return printBundle(node);
+ case 286: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -66808,7 +68052,7 @@
return endPrint();
}
function printBundle(bundle) {
- writeBundle(bundle, undefined, beginPrint(), undefined);
+ writeBundle(bundle, beginPrint(), undefined);
return endPrint();
}
function printFile(sourceFile) {
@@ -66836,7 +68080,49 @@
reset();
writer = previousWriter;
}
- function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) {
+ function getTextPosWithWriteLine() {
+ return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
+ }
+ function updateOrPushBundleFileTextLike(pos, end, kind) {
+ var last = ts.lastOrUndefined(bundleFileInfo.sections);
+ if (last && last.kind === kind) {
+ last.end = end;
+ }
+ else {
+ bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
+ }
+ }
+ function recordBundleFileInternalSectionStart(node) {
+ if (recordInternalSection &&
+ bundleFileInfo &&
+ currentSourceFile &&
+ (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
+ ts.isInternalDeclaration(node, currentSourceFile) &&
+ sourceFileTextKind !== "internal") {
+ var prevSourceFileTextKind = sourceFileTextKind;
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = "internal";
+ return prevSourceFileTextKind;
+ }
+ return undefined;
+ }
+ function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
+ if (prevSourceFileTextKind) {
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = prevSourceFileTextKind;
+ }
+ }
+ function recordBundleFileTextLikeSection(end) {
+ if (sourceFileTextPos < end) {
+ updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
+ return true;
+ }
+ return false;
+ }
+ function writeBundle(bundle, output, sourceMapGenerator) {
+ var _a;
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output, sourceMapGenerator);
@@ -66844,18 +68130,47 @@
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
- var prepend = _b[_a];
+ for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
+ var prepend = _c[_b];
writeLine();
+ var pos = writer.getTextPos();
+ var savedSections = bundleFileInfo && bundleFileInfo.sections;
+ if (savedSections)
+ bundleFileInfo.sections = [];
print(4, prepend, undefined);
+ if (bundleFileInfo) {
+ var newSections = bundleFileInfo.sections;
+ bundleFileInfo.sections = savedSections;
+ if (prepend.oldFileOfCurrentEmit)
+ (_a = bundleFileInfo.sections).push.apply(_a, newSections);
+ else {
+ newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prepend", data: prepend.fileName, texts: newSections });
}
- if (bundleInfo) {
- bundleInfo.originalOffset = writer.getTextPos();
}
- for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
- var sourceFile = _d[_c];
+ }
+ sourceFileTextPos = getTextPosWithWriteLine();
+ for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
+ var sourceFile = _e[_d];
print(0, sourceFile, sourceFile);
}
+ if (bundleFileInfo && bundle.sourceFiles.length) {
+ var end = writer.getTextPos();
+ if (recordBundleFileTextLikeSection(end)) {
+ var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
+ if (prologues) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.prologues = prologues;
+ }
+ var helpers = getHelpersFromBundledSourceFiles(bundle);
+ if (helpers) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.helpers = helpers;
+ }
+ }
+ }
reset();
writer = previousWriter;
}
@@ -66925,8 +68240,10 @@
function emit(node) {
if (node === undefined)
return;
+ var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
var pipelinePhase = getPipelinePhase(0, node);
pipelinePhase(4, node);
+ recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
}
function emitIdentifierName(node) {
if (node === undefined)
@@ -66951,11 +68268,11 @@
return pipelineEmitWithSubstitution;
}
case 2:
- if (!commentsDisabled && node.kind !== 279) {
+ if (!commentsDisabled && node.kind !== 284) {
return pipelineEmitWithComments;
}
case 3:
- if (!sourceMapsDisabled && node.kind !== 279 && !ts.isInJsonFile(node)) {
+ if (!sourceMapsDisabled && node.kind !== 284 && !ts.isInJsonFile(node)) {
return pipelineEmitWithSourceMap;
}
case 4:
@@ -66990,8 +68307,16 @@
case 16:
case 17:
return emitLiteral(node);
+ case 286:
+ case 280:
+ return emitUnparsedSourceOrPrepend(node);
+ case 279:
+ return writeUnparsedNode(node);
case 281:
- return emitUnparsedSource(node);
+ case 282:
+ return emitUnparsedTextLike(node);
+ case 283:
+ return emitUnparsedSyntheticReference(node);
case 72:
return emitIdentifier(node);
case 148:
@@ -67029,7 +68354,7 @@
return emitTypeReference(node);
case 165:
return emitFunctionType(node);
- case 289:
+ case 294:
return emitJSDocFunctionType(node);
case 166:
return emitConstructorType(node);
@@ -67067,20 +68392,20 @@
return emitLiteralType(node);
case 183:
return emitImportTypeNode(node);
- case 284:
+ case 289:
writePunctuation("*");
return;
- case 285:
+ case 290:
writePunctuation("?");
return;
- case 286:
+ case 291:
return emitJSDocNullableType(node);
- case 287:
+ case 292:
return emitJSDocNonNullableType(node);
- case 288:
+ case 293:
return emitJSDocOptionalType(node);
case 172:
- case 290:
+ case 295:
return emitRestOrJSDocVariadicType(node);
case 184:
return emitObjectBindingPattern(node);
@@ -67208,30 +68533,30 @@
return emitSpreadAssignment(node);
case 278:
return emitEnumMember(node);
- case 299:
- case 305:
+ case 304:
+ case 310:
return emitJSDocPropertyLikeTag(node);
- case 300:
- case 302:
- case 301:
- case 298:
+ case 305:
+ case 307:
+ case 306:
+ case 303:
return emitJSDocSimpleTypedTag(node);
- case 295:
+ case 300:
return emitJSDocAugmentsTag(node);
- case 303:
+ case 308:
return emitJSDocTemplateTag(node);
- case 304:
+ case 309:
return emitJSDocTypedefTag(node);
- case 297:
+ case 302:
return emitJSDocCallbackTag(node);
- case 293:
+ case 298:
return emitJSDocSignature(node);
- case 292:
+ case 297:
return emitJSDocTypeLiteral(node);
- case 296:
- case 294:
+ case 301:
+ case 299:
return emitJSDocSimpleTag(node);
- case 291:
+ case 296:
return emitJSDoc(node);
}
if (ts.isExpression(node)) {
@@ -67323,9 +68648,9 @@
return emitJsxSelfClosingElement(node);
case 264:
return emitJsxFragment(node);
- case 308:
+ case 313:
return emitPartiallyEmittedExpression(node);
- case 309:
+ case 314:
return emitCommaList(node);
}
}
@@ -67341,22 +68666,45 @@
var pipelinePhase = getNextPipelinePhase(1, node);
pipelinePhase(hint, substituteNode(hint, node));
}
+ function getHelpersFromBundledSourceFiles(bundle) {
+ var result;
+ if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
+ return undefined;
+ }
+ var bundledHelpers = ts.createMap();
+ for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
+ var helpers = getSortedEmitHelpers(sourceFile);
+ if (!helpers)
+ continue;
+ for (var _c = 0, helpers_3 = helpers; _c < helpers_3.length; _c++) {
+ var helper = helpers_3[_c];
+ if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
+ bundledHelpers.set(helper.name, true);
+ (result || (result = [])).push(helper.name);
+ }
+ }
+ }
+ return result;
+ }
function emitHelpers(node) {
var helpersEmitted = false;
- var bundle = node.kind === 280 ? node : undefined;
+ var bundle = node.kind === 285 ? node : undefined;
if (bundle && moduleKind === ts.ModuleKind.None) {
return;
}
- var numNodes = bundle ? bundle.sourceFiles.length : 1;
+ var numPrepends = bundle ? bundle.prepends.length : 0;
+ var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
for (var i = 0; i < numNodes; i++) {
- var currentNode = bundle ? bundle.sourceFiles[i] : node;
- var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile;
- var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined;
- var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit;
- var helpers = ts.getEmitHelpers(currentNode);
+ var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
+ var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
+ var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
+ var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
+ var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
if (helpers) {
- for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
- var helper = _b[_a];
+ for (var _a = 0, helpers_4 = helpers; _a < helpers_4.length; _a++) {
+ var helper = helpers_4[_a];
if (!helper.scoped) {
if (shouldSkip)
continue;
@@ -67370,18 +68718,25 @@
else if (bundle) {
continue;
}
+ var pos = getTextPosWithWriteLine();
if (typeof helper.text === "string") {
writeLines(helper.text);
}
else {
writeLines(helper.text(makeFileLevelOptimisticUniqueName));
}
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers", data: helper.name });
helpersEmitted = true;
}
}
}
return helpersEmitted;
}
+ function getSortedEmitHelpers(node) {
+ var helpers = ts.getEmitHelpers(node);
+ return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
+ }
function emitNumericOrBigIntLiteral(node) {
emitLiteral(node);
}
@@ -67395,8 +68750,34 @@
writeStringLiteral(text);
}
}
- function emitUnparsedSource(unparsed) {
- writer.rawWrite(unparsed.text);
+ function emitUnparsedSourceOrPrepend(unparsed) {
+ for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
+ var text = _b[_a];
+ writeLine();
+ emit(text);
+ }
+ }
+ function writeUnparsedNode(unparsed) {
+ writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
+ }
+ function emitUnparsedTextLike(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 281 ?
+ "text" :
+ "internal");
+ }
+ }
+ function emitUnparsedSyntheticReference(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ var section = ts.clone(unparsed.section);
+ section.pos = pos;
+ section.end = writer.getTextPos();
+ bundleFileInfo.sections.push(section);
+ }
}
function emitIdentifier(node) {
var writeText = node.symbol ? writeSymbol : write;
@@ -67442,7 +68823,7 @@
emit(node.dotDotDotToken);
emitNodeWithWriter(node.name, writeParameter);
emit(node.questionToken);
- if (node.parent && node.parent.kind === 289 && !node.name) {
+ if (node.parent && node.parent.kind === 294 && !node.name) {
emit(node.type);
}
else {
@@ -68268,7 +69649,7 @@
emitBlockFunctionBodyWorker(body, true);
}
function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
- var statementOffset = emitPrologueDirectives(body.statements, true);
+ var statementOffset = emitPrologueDirectives(body.statements);
var pos = writer.getTextPos();
emitHelpers(body);
if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
@@ -68522,7 +69903,7 @@
writePunctuation(">");
}
function emitJsxText(node) {
- writer.writeLiteral(getTextOfNode(node, true));
+ writer.writeLiteral(node.text);
}
function emitJsxClosingElementOrFragment(node) {
writePunctuation("</");
@@ -68646,7 +70027,7 @@
}
}
if (node.tags) {
- if (node.tags.length === 1 && node.tags[0].kind === 302 && !node.comment) {
+ if (node.tags.length === 1 && node.tags[0].kind === 307 && !node.comment) {
writeSpace();
emit(node.tags[0]);
}
@@ -68680,7 +70061,7 @@
function emitJSDocTypedefTag(tag) {
emitJSDocTagName(tag.tagName);
if (tag.typeExpression) {
- if (tag.typeExpression.kind === 283) {
+ if (tag.typeExpression.kind === 288) {
emitJSDocTypeExpression(tag.typeExpression);
}
else {
@@ -68699,7 +70080,7 @@
emit(tag.fullName);
}
emitJSDocComment(tag.comment);
- if (tag.typeExpression && tag.typeExpression.kind === 292) {
+ if (tag.typeExpression && tag.typeExpression.kind === 297) {
emitJSDocTypeLiteral(tag.typeExpression);
}
}
@@ -68781,6 +70162,16 @@
}
function emitSyntheticTripleSlashReferencesIfNeeded(node) {
emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
+ for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
+ for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
+ var ref = _d[_c];
+ emit(ref);
+ writeLine();
+ }
+ }
+ }
}
function emitTripleSlashDirectivesIfNeeded(node) {
if (node.isDeclarationFile)
@@ -68788,7 +70179,10 @@
}
function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
if (hasNoDefaultLib) {
+ var pos = writer.getTextPos();
writeComment("/// <reference no-default-lib=\"true\"/>");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" });
writeLine();
}
if (currentSourceFile && currentSourceFile.moduleName) {
@@ -68809,17 +70203,26 @@
}
for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
var directive = files_1[_c];
+ var pos = writer.getTextPos();
writeComment("/// <reference path=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference", data: directive.fileName });
writeLine();
}
- for (var _d = 0, types_18 = types; _d < types_18.length; _d++) {
- var directive = types_18[_d];
+ for (var _d = 0, types_19 = types; _d < types_19.length; _d++) {
+ var directive = types_19[_d];
+ var pos = writer.getTextPos();
writeComment("/// <reference types=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type", data: directive.fileName });
writeLine();
}
for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
var directive = libs_1[_e];
+ var pos = writer.getTextPos();
writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib", data: directive.fileName });
writeLine();
}
}
@@ -68839,16 +70242,22 @@
function emitCommaList(node) {
emitExpressionList(node, node.elements, 528);
}
- function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) {
+ function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
+ var needsToSetSourceFile = !!sourceFile;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (ts.isPrologueDirective(statement)) {
var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
if (shouldEmitPrologueDirective) {
- if (startWithNewLine || i > 0) {
- writeLine();
+ if (needsToSetSourceFile) {
+ needsToSetSourceFile = false;
+ setSourceFile(sourceFile);
}
+ writeLine();
+ var pos = writer.getTextPos();
emit(statement);
+ if (recordBundleFileSection && bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue", data: statement.expression.text });
if (seenPrologueDirectives) {
seenPrologueDirectives.set(statement.expression.text, true);
}
@@ -68860,23 +70269,70 @@
}
return statements.length;
}
+ function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
+ for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
+ var prologue = prologues_1[_a];
+ if (!seenPrologueDirectives.has(prologue.data)) {
+ writeLine();
+ var pos = writer.getTextPos();
+ emit(prologue);
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue", data: prologue.data });
+ if (seenPrologueDirectives) {
+ seenPrologueDirectives.set(prologue.data, true);
+ }
+ }
+ }
+ }
function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
if (ts.isSourceFile(sourceFileOrBundle)) {
- setSourceFile(sourceFileOrBundle);
- emitPrologueDirectives(sourceFileOrBundle.statements);
+ emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
}
else {
var seenPrologueDirectives = ts.createMap();
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
- setSourceFile(sourceFile);
- emitPrologueDirectives(sourceFile.statements, true, seenPrologueDirectives);
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
+ emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, true);
}
setSourceFile(undefined);
}
}
+ function getPrologueDirectivesFromBundledSourceFiles(bundle) {
+ var seenPrologueDirectives = ts.createMap();
+ var prologues;
+ for (var index = 0; index < bundle.sourceFiles.length; index++) {
+ var sourceFile = bundle.sourceFiles[index];
+ var directives = void 0;
+ var end = 0;
+ for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
+ var statement = _b[_a];
+ if (!ts.isPrologueDirective(statement))
+ break;
+ if (seenPrologueDirectives.has(statement.expression.text))
+ continue;
+ seenPrologueDirectives.set(statement.expression.text, true);
+ (directives || (directives = [])).push({
+ pos: statement.pos,
+ end: statement.end,
+ expression: {
+ pos: statement.expression.pos,
+ end: statement.expression.end,
+ text: statement.expression.text
+ }
+ });
+ end = end < statement.end ? statement.end : end;
+ }
+ if (directives)
+ (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
+ }
+ return prologues;
+ }
function emitShebangIfNeeded(sourceFileOrBundle) {
- if (ts.isSourceFile(sourceFileOrBundle)) {
+ if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
var shebang = ts.getShebang(sourceFileOrBundle.text);
if (shebang) {
writeComment(shebang);
@@ -68885,10 +70341,17 @@
}
}
else {
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ ts.Debug.assertNode(prepend, ts.isUnparsedSource);
+ if (emitShebangIfNeeded(prepend)) {
+ return true;
+ }
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
if (emitShebangIfNeeded(sourceFile)) {
- break;
+ return true;
}
}
}
@@ -69083,6 +70546,7 @@
increaseIndent();
}
var previousSibling = void 0;
+ var previousSourceFileTextKind = void 0;
var shouldDecreaseIndentAfterEmit = false;
for (var i = 0; i < count; i++) {
var child = children[start + i];
@@ -69095,6 +70559,7 @@
emitLeadingCommentsOfPosition(previousSibling.end);
}
writeDelimiter(format);
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
if ((format & (3 | 128)) === 0) {
increaseIndent();
@@ -69107,6 +70572,7 @@
writeSpace();
}
}
+ previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
if (shouldEmitInterveningComments) {
if (emitTrailingCommentsOfPosition) {
var commentRange = ts.getCommentRange(child);
@@ -69133,6 +70599,7 @@
if (format & 128) {
decreaseIndent();
}
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
writeLine();
}
@@ -69231,7 +70698,6 @@
if (line.length) {
writeLine();
write(line);
- writer.rawWrite(newLine);
}
}
}
@@ -69676,7 +71142,7 @@
hasWrittenComment = false;
var emitFlags = ts.getEmitFlags(node);
var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
- var isEmittedNode = node.kind !== 307;
+ var isEmittedNode = node.kind !== 312;
var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0 || node.kind === 11;
var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 11;
var savedContainerPos = containerPos;
@@ -69904,19 +71370,28 @@
function isTripleSlashComment(commentPos, commentEnd) {
return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
}
+ function getParsedSourceMap(node) {
+ if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
+ node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
+ }
+ return node.parsedSourceMap || undefined;
+ }
function pipelineEmitWithSourceMap(hint, node) {
var pipelinePhase = getNextPipelinePhase(3, node);
- if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) {
- var parsed = ts.tryParseRawSourceMap(node.sourceMapText);
- if (parsed) {
- sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath);
+ if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
+ pipelinePhase(hint, node);
+ }
+ else if (ts.isUnparsedNode(node)) {
+ var parsed = getParsedSourceMap(node.parent);
+ if (parsed && sourceMapGenerator) {
+ sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
}
pipelinePhase(hint, node);
}
else {
var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
var emitFlags = ts.getEmitFlags(node);
- if (node.kind !== 307
+ if (node.kind !== 312
&& (emitFlags & 16) === 0
&& pos >= 0) {
emitSourcePos(source, skipSourceTrivia(source, pos));
@@ -69929,7 +71404,7 @@
else {
pipelinePhase(hint, node);
}
- if (node.kind !== 307
+ if (node.kind !== 312
&& (emitFlags & 32) === 0
&& end >= 0) {
emitSourcePos(source, end);
@@ -70029,7 +71504,8 @@
writeFile: host.writeFile && writeFile,
addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
addOrDeleteFile: addOrDeleteFile,
- clearCache: clearCache
+ clearCache: clearCache,
+ realpath: host.realpath && realpath
};
function toPath(fileName) {
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
@@ -70120,7 +71596,7 @@
var rootDirPath = toPath(rootDir);
var result = tryReadDirectory(rootDir, rootDirPath);
if (result) {
- return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries);
+ return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
}
return host.readDirectory(rootDir, extensions, excludes, includes, depth);
function getFileSystemEntries(dir) {
@@ -70131,6 +71607,9 @@
return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
}
}
+ function realpath(s) {
+ return host.realpath ? host.realpath(s) : s;
+ }
function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
if (existingResult) {
@@ -70365,9 +71844,7 @@
function createCompilerHostWorker(options, setParentNodes, system) {
if (system === void 0) { system = ts.sys; }
var existingDirectories = ts.createMap();
- function getCanonicalFileName(fileName) {
- return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
- }
+ var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
function getSourceFile(fileName, languageVersion, onError) {
var text;
try {
@@ -70490,20 +71967,20 @@
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
- return value || undefined;
+ return value !== false ? value : undefined;
return setReadFileCache(key, fileName);
};
var setReadFileCache = function (key, fileName) {
var newValue = originalReadFile.call(host, fileName);
- readFileCache.set(key, newValue || false);
+ readFileCache.set(key, newValue !== undefined ? newValue : false);
return newValue;
};
host.readFile = function (fileName) {
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
- return value;
- if (!ts.fileExtensionIs(fileName, ".json")) {
+ return value !== false ? value : undefined;
+ if (!ts.fileExtensionIs(fileName, ".json") && !ts.isBuildInfoFile(fileName)) {
return originalReadFile.call(host, fileName);
}
return setReadFileCache(key, fileName);
@@ -70533,7 +72010,7 @@
var key = toPath(fileName);
fileExistsCache.delete(key);
var value = readFileCache.get(key);
- if (value && value !== data) {
+ if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.delete(key);
}
@@ -70919,11 +72396,18 @@
if (rootNames.length) {
for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
var parsedRef = resolvedProjectReferences_1[_i];
- if (parsedRef) {
+ if (!parsedRef)
+ continue;
var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
if (out) {
- var dtsOutfile = ts.changeExtension(out, ".d.ts");
- processSourceFile(dtsOutfile, false, false, undefined);
+ processSourceFile(ts.changeExtension(out, ".d.ts"), false, false, undefined);
+ }
+ else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
+ for (var _a = 0, _b = parsedRef.commandLine.fileNames; _a < _b.length; _a++) {
+ var fileName = _b[_a];
+ if (!ts.fileExtensionIs(fileName, ".d.ts") && ts.hasTSFileExtension(fileName)) {
+ processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), false, false, undefined);
+ }
}
}
}
@@ -70961,8 +72445,8 @@
ts.Debug.assert(!!missingFilePaths);
if (oldProgram && host.onReleaseOldSourceFile) {
var oldSourceFiles = oldProgram.getSourceFiles();
- for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) {
- var oldSourceFile = oldSourceFiles_1[_a];
+ for (var _c = 0, oldSourceFiles_1 = oldSourceFiles; _c < oldSourceFiles_1.length; _c++) {
+ var oldSourceFile = oldSourceFiles_1[_c];
var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
if (shouldCreateNewSourceFile || !newFile ||
(oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) {
@@ -71016,7 +72500,8 @@
getProjectReferenceRedirect: getProjectReferenceRedirect,
getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
- forEachResolvedProjectReference: forEachResolvedProjectReference
+ forEachResolvedProjectReference: forEachResolvedProjectReference,
+ emitBuildInfo: emitBuildInfo
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -71045,7 +72530,7 @@
}
function getCommonSourceDirectory() {
if (commonSourceDirectory === undefined) {
- var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); });
+ var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
}
@@ -71342,14 +72827,23 @@
}
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, getLibFileFromReference: program.getLibFileFromReference, 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) {
+ 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, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
+ getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, 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) {
var path = toPath(f);
if (getSourceFileByPath(path))
return true;
if (ts.contains(missingFilePaths, path))
return false;
return host.fileExists(f);
- } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } });
+ } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); } });
+ }
+ function emitBuildInfo(writeFileCallback) {
+ ts.Debug.assert(!options.out && !options.outFile);
+ ts.performance.mark("beforeEmit");
+ var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), undefined, false, undefined, undefined, true);
+ ts.performance.mark("afterEmit");
+ ts.performance.measure("Emit", "beforeEmit", "afterEmit");
+ return emitResult;
}
function getResolvedProjectReferences() {
return resolvedProjectReferences;
@@ -71358,27 +72852,11 @@
return projectReferences;
}
function getPrependNodes() {
- if (!projectReferences) {
- return ts.emptyArray;
- }
- var nodes = [];
- for (var i = 0; i < projectReferences.length; i++) {
- var ref = projectReferences[i];
- var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
- if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
- var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
- if (!out)
- continue;
- var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- var node = ts.createInputFiles(function (fileName) {
+ return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
var path = toPath(fileName);
var sourceFile = getSourceFileByPath(path);
return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
- }, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath);
- nodes.push(node);
- }
- }
- return nodes;
+ });
}
function isSourceFileFromExternalLibrary(file) {
return !!sourceFilesFoundSearchingNodeModules.get(file.path);
@@ -71986,7 +73464,6 @@
if (refFile) {
var redirect = getProjectReferenceRedirect(fileName);
if (redirect) {
- (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName);
fileName = redirect;
redirectedPath = toPath(redirect);
}
@@ -72069,7 +73546,7 @@
var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
return out ?
ts.changeExtension(out, ".d.ts") :
- ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine);
+ ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
}
function getResolvedProjectReferenceToRedirect(fileName) {
if (mapFromFileToProjectReferenceRedirects === undefined) {
@@ -72334,17 +73811,26 @@
if (options.declaration === false) {
createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
}
+ if (options.incremental === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
+ }
+ }
+ if (options.tsBuildInfoFile) {
+ if (!ts.isIncrementalCompilation(options)) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
+ }
}
verifyProjectReferences();
if (options.composite) {
- var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; });
- if (rootNames.length < sourceFiles.length) {
- var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); });
- for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) {
- var file = _a[_i];
- if (normalizedRootNames.indexOf(file) === -1) {
- 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));
- }
+ var rootPaths = rootNames.map(toPath);
+ for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
+ var file = files_3[_i];
+ if (file.isDeclarationFile)
+ continue;
+ if (ts.isJsonSourceFile(file) && getResolvedProjectReferenceToRedirect(file.fileName))
+ continue;
+ if (rootPaths.indexOf(file.path) === -1) {
+ 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.fileName));
}
}
}
@@ -72513,6 +73999,7 @@
}
}
function verifyProjectReferences() {
+ var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getOutputPathForBuildInfo(options) : undefined;
forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
var parentFile = parent && parent.sourceFile;
@@ -72538,6 +74025,10 @@
createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
}
}
+ if (!parent && buildInfoPath && buildInfoPath === ts.getOutputPathForBuildInfo(options)) {
+ createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
+ hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
+ }
});
}
function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
@@ -72676,11 +74167,30 @@
readFile: function (f) { return directoryStructureHost.readFile(f); },
useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
getCurrentDirectory: function () { return host.getCurrentDirectory(); },
- onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || (function () { return undefined; }),
+ onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
trace: host.trace ? function (s) { return host.trace(s); } : undefined
};
}
ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
+ function createPrependNodes(projectReferences, getCommandLine, readFile) {
+ if (!projectReferences)
+ return ts.emptyArray;
+ var nodes;
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = getCommandLine(ref, i);
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
+ if (!out)
+ continue;
+ var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
+ (nodes || (nodes = [])).push(node);
+ }
+ }
+ return nodes || ts.emptyArray;
+ }
+ ts.createPrependNodes = createPrependNodes;
function resolveProjectReferencePath(hostOrRef, ref) {
var passedInRef = ref ? ref : hostOrRef;
return ts.resolveConfigFileProjectName(passedInRef.path);
@@ -72839,7 +74349,7 @@
var useOldState = canReuseOldState(referencedMap, oldState);
for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
- var version_1 = sourceFile.version;
+ var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined;
if (referencedMap) {
var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
@@ -73102,10 +74612,13 @@
var affectedSignatures = oldState.currentAffectedFilesSignatures;
ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
}
+ var changedFilesSet = oldState.changedFilesSet;
if (canCopySemanticDiagnostics) {
- ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
+ ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
+ }
+ if (changedFilesSet) {
+ ts.copyEntries(changedFilesSet, state.changedFilesSet);
}
- ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet);
if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit;
state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
@@ -73135,7 +74648,7 @@
}
var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
if (diagnostics) {
- state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics);
+ state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics);
if (!state.semanticDiagnosticsFromOldState) {
state.semanticDiagnosticsFromOldState = ts.createMap();
}
@@ -73143,8 +74656,44 @@
}
}
});
+ if (oldCompilerOptions &&
+ (oldCompilerOptions.outDir !== compilerOptions.outDir ||
+ oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
+ (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
+ state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(function (f) { return f.path; }));
+ if (state.affectedFilesPendingEmitIndex === undefined) {
+ state.affectedFilesPendingEmitIndex = 0;
+ }
+ ts.Debug.assert(state.seenAffectedFiles === undefined);
+ state.seenAffectedFiles = ts.createMap();
+ }
return state;
}
+ function convertToDiagnostics(diagnostics, newProgram) {
+ if (!diagnostics.length)
+ return ts.emptyArray;
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToDiagnosticRelatedInformation(diagnostic, newProgram) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && newProgram.getSourceFileByPath(file), messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToDiagnosticMessageChain(messageText, newProgram) });
+ }
+ function convertToDiagnosticMessageChain(diagnostic, newProgram) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram) });
+ }
function releaseCache(state) {
ts.BuilderState.releaseCache(state);
state.program = undefined;
@@ -73306,8 +74855,11 @@
state.semanticDiagnosticsPerFile.delete(path);
return !state.semanticDiagnosticsFromOldState.size;
}
- function doneWithAffectedFile(state, affected, isPendingEmit) {
- if (affected === state.program) {
+ function doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit) {
+ if (isBuildInfoEmit) {
+ state.emittedBuildInfo = true;
+ }
+ else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
@@ -73321,8 +74873,8 @@
}
}
}
- function toAffectedFileResult(state, result, affected, isPendingEmit) {
- doneWithAffectedFile(state, affected, isPendingEmit);
+ function toAffectedFileResult(state, result, affected, isPendingEmit, isBuildInfoEmit) {
+ doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
return { result: result, affected: affected };
}
function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
@@ -73339,6 +74891,71 @@
}
return diagnostics;
}
+ function getProgramBuildInfo(state) {
+ if (state.compilerOptions.outFile || state.compilerOptions.out)
+ return undefined;
+ var fileInfos = {};
+ state.fileInfos.forEach(function (value, key) {
+ var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
+ fileInfos[key] = signature === undefined ? value : { version: value.version, signature: signature };
+ });
+ var result = { fileInfos: fileInfos, options: state.compilerOptions };
+ if (state.referencedMap) {
+ var referencedMap_1 = {};
+ state.referencedMap.forEach(function (value, key) {
+ referencedMap_1[key] = ts.arrayFrom(value.keys());
+ });
+ result.referencedMap = referencedMap_1;
+ }
+ if (state.exportedModulesMap) {
+ var exportedModulesMap_1 = {};
+ state.exportedModulesMap.forEach(function (value, key) {
+ var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
+ if (newValue === undefined)
+ exportedModulesMap_1[key] = ts.arrayFrom(value.keys());
+ else if (newValue)
+ exportedModulesMap_1[key] = ts.arrayFrom(newValue.keys());
+ });
+ result.exportedModulesMap = exportedModulesMap_1;
+ }
+ if (state.semanticDiagnosticsPerFile) {
+ var semanticDiagnosticsPerFile_1 = [];
+ state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ?
+ [
+ key,
+ state.hasReusableDiagnostic ?
+ value :
+ convertToReusableDiagnostics(value)
+ ] :
+ key); });
+ result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1;
+ }
+ return result;
+ }
+ function convertToReusableDiagnostics(diagnostics) {
+ ts.Debug.assert(!!diagnostics.length);
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToReusableDiagnosticRelatedInformation(diagnostic);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToReusableDiagnosticRelatedInformation(diagnostic) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && file.path, messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToReusableDiagnosticMessageChain(messageText) });
+ }
+ function convertToReusableDiagnosticMessageChain(diagnostic) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next) });
+ }
var BuilderProgramKind;
(function (BuilderProgramKind) {
BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
@@ -73388,6 +75005,7 @@
var computeHash = host.createHash || ts.generateDjb2Hash;
var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
var backupState;
+ newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state); };
newProgram = undefined;
oldProgram = undefined;
oldState = undefined;
@@ -73425,8 +75043,12 @@
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
affected = getNextAffectedFilePendingEmit(state);
if (!affected) {
+ if (state.emittedBuildInfo) {
return undefined;
}
+ var affected_1 = ts.Debug.assertDefined(state.program);
+ return toAffectedFileResult(state, affected_1.emitBuildInfo(writeFile || host.writeFile, cancellationToken), affected_1, false, true);
+ }
isPendingEmitFile = true;
}
else {
@@ -73510,13 +75132,58 @@
}
var diagnostics;
for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
- var sourceFile_2 = _a[_i];
- diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken));
+ var sourceFile_1 = _a[_i];
+ diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
}
return diagnostics || ts.emptyArray;
}
}
ts.createBuilderProgram = createBuilderProgram;
+ function getMapOfReferencedSet(mapLike) {
+ if (!mapLike)
+ return undefined;
+ var map = ts.createMap();
+ for (var key in mapLike) {
+ if (ts.hasProperty(mapLike, key)) {
+ map.set(key, ts.arrayToSet(mapLike[key]));
+ }
+ }
+ return map;
+ }
+ function createBuildProgramUsingProgramBuildInfo(program) {
+ var fileInfos = ts.createMapFromTemplate(program.fileInfos);
+ var state = {
+ fileInfos: fileInfos,
+ compilerOptions: program.options,
+ referencedMap: getMapOfReferencedSet(program.referencedMap),
+ exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
+ semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return ts.isString(value) ? value : value[0]; }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
+ hasReusableDiagnostic: true
+ };
+ return {
+ getState: function () { return state; },
+ backupState: ts.noop,
+ restoreState: ts.noop,
+ getProgram: ts.notImplemented,
+ getProgramOrUndefined: ts.returnUndefined,
+ releaseProgram: ts.noop,
+ getCompilerOptions: function () { return state.compilerOptions; },
+ getSourceFile: ts.notImplemented,
+ getSourceFiles: ts.notImplemented,
+ getOptionsDiagnostics: ts.notImplemented,
+ getGlobalDiagnostics: ts.notImplemented,
+ getConfigFileParsingDiagnostics: ts.notImplemented,
+ getSyntacticDiagnostics: ts.notImplemented,
+ getDeclarationDiagnostics: ts.notImplemented,
+ getSemanticDiagnostics: ts.notImplemented,
+ emit: ts.notImplemented,
+ getAllDependencies: ts.notImplemented,
+ getCurrentDirectory: ts.notImplemented,
+ emitNextAffectedFile: ts.notImplemented,
+ getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
+ };
+ }
+ ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
return {
getState: ts.notImplemented,
@@ -73536,7 +75203,7 @@
getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
getAllDependencies: ts.notImplemented,
- getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); }
+ getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
};
function getProgram() {
return ts.Debug.assertDefined(state.program);
@@ -73561,10 +75228,10 @@
})(ts || (ts = {}));
var ts;
(function (ts) {
- function isPathInNodeModulesStartingWithDot(path) {
- return ts.stringContains(path, "/node_modules/.");
+ function isPathIgnored(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); });
}
- ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot;
+ ts.isPathIgnored = isPathIgnored;
ts.maxNumberOfFilesToIterateForInvalidation = 256;
function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
var filesWithChangedSetOfUnresolvedImports;
@@ -74024,7 +75691,7 @@
isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); };
}
else {
- if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (isPathIgnored(fileOrDirectoryPath))
return false;
var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) ||
@@ -74428,6 +76095,8 @@
case ".jsx":
case ".json":
return ext;
+ case ".tsbuildinfo":
+ return ts.Debug.fail("Extension " + ".tsbuildinfo" + " is unsupported:: FileName:: " + fileName);
default:
return ts.Debug.assertNever(ext);
}
@@ -74533,19 +76202,15 @@
var diagnostics = program.getConfigFileParsingDiagnostics().slice();
var configFileParsingDiagnosticsLength = diagnostics.length;
ts.addRange(diagnostics, program.getSyntacticDiagnostics());
- var reportSemanticDiagnostics = false;
if (diagnostics.length === configFileParsingDiagnosticsLength) {
ts.addRange(diagnostics, program.getOptionsDiagnostics());
ts.addRange(diagnostics, program.getGlobalDiagnostics());
if (diagnostics.length === configFileParsingDiagnosticsLength) {
- reportSemanticDiagnostics = true;
+ ts.addRange(diagnostics, program.getSemanticDiagnostics());
}
}
var _a = program.emit(undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics;
ts.addRange(diagnostics, emitDiagnostics);
- if (reportSemanticDiagnostics) {
- ts.addRange(diagnostics, program.getSemanticDiagnostics());
- }
ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic);
if (writeFileName) {
var currentDir_1 = program.getCurrentDirectory();
@@ -74654,6 +76319,22 @@
}
}
ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
+ function setGetSourceFileAsHashVersioned(compilerHost, host) {
+ var originalGetSourceFile = compilerHost.getSourceFile;
+ var computeHash = host.createHash || ts.generateDjb2Hash;
+ compilerHost.getSourceFile = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
+ if (result) {
+ result.version = computeHash.call(host, result.text);
+ }
+ return result;
+ };
+ }
+ ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
function createProgramHost(system, createProgram) {
var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); });
var host = system;
@@ -74676,14 +76357,14 @@
writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
createHash: ts.maybeBind(system, system.createHash),
- createProgram: createProgram
+ createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
};
}
ts.createProgramHost = createProgramHost;
function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
var writeFileName = function (s) { return system.write(s + system.newLine); };
- var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram);
+ var result = createProgramHost(system, createProgram);
ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = function (builderProgram) {
var compilerOptions = builderProgram.getCompilerOptions();
@@ -74713,6 +76394,49 @@
return host;
}
ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
+ function readBuilderProgram(compilerOptions, readFile) {
+ if (compilerOptions.out || compilerOptions.outFile)
+ return undefined;
+ var buildInfoPath = ts.getOutputPathForBuildInfo(compilerOptions);
+ if (!buildInfoPath)
+ return undefined;
+ var content = readFile(buildInfoPath);
+ if (!content)
+ return undefined;
+ var buildInfo = ts.getBuildInfo(content);
+ if (buildInfo.version !== ts.version)
+ return undefined;
+ if (!buildInfo.program)
+ return undefined;
+ return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program);
+ }
+ ts.readBuilderProgram = readBuilderProgram;
+ function createIncrementalCompilerHost(options, system) {
+ if (system === void 0) { system = ts.sys; }
+ var host = ts.createCompilerHostWorker(options, undefined, system);
+ host.createHash = ts.maybeBind(system, system.createHash);
+ setGetSourceFileAsHashVersioned(host, system);
+ ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
+ return host;
+ }
+ ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
+ function createIncrementalProgram(_a) {
+ var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
+ host = host || createIncrementalCompilerHost(options);
+ createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
+ var oldProgram = readBuilderProgram(options, function (path) { return host.readFile(path); });
+ return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
+ }
+ function performIncrementalCompilation(input) {
+ var system = input.system || ts.sys;
+ var host = input.host || (input.host = createIncrementalCompilerHost(input.options, system));
+ var builderProgram = createIncrementalProgram(input);
+ var exitStatus = emitFilesAndReportErrors(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined);
+ if (input.afterProgramEmitAndDiagnostics)
+ input.afterProgramEmitAndDiagnostics(builderProgram);
+ return exitStatus;
+ }
+ ts.performIncrementalCompilation = performIncrementalCompilation;
})(ts || (ts = {}));
(function (ts) {
function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) {
@@ -74724,7 +76448,6 @@
}
}
ts.createWatchCompilerHost = createWatchCompilerHost;
- var initialVersion = 1;
function createWatchProgram(host) {
var builderProgram;
var reloadLevel;
@@ -74764,10 +76487,12 @@
var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
+ var configFileWatcher;
if (configFileName) {
- watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file");
+ configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file");
}
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
+ ts.setGetSourceFileAsHashVersioned(compilerHost, host);
var getNewSourceFile = compilerHost.getSourceFile;
compilerHost.getSourceFile = function (fileName) {
var args = [];
@@ -74803,20 +76528,42 @@
(function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) :
(function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
+ builderProgram = ts.readBuilderProgram(compilerOptions, function (path) { return compilerHost.readFile(path); });
synchronizeProgram();
watchConfigFileWildCardDirectories();
return configFileName ?
- { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } :
- { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames };
+ { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } :
+ { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close };
+ function close() {
+ resolutionCache.clear();
+ ts.clearMap(sourceFilesCache, function (value) {
+ if (value && value.fileWatcher) {
+ value.fileWatcher.close();
+ value.fileWatcher = undefined;
+ }
+ });
+ if (configFileWatcher) {
+ configFileWatcher.close();
+ configFileWatcher = undefined;
+ }
+ if (watchedWildcardDirectories) {
+ ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
+ watchedWildcardDirectories = undefined;
+ }
+ if (missingFilesMap) {
+ ts.clearMap(missingFilesMap, ts.closeFileWatcher);
+ missingFilesMap = undefined;
+ }
+ }
function getCurrentBuilderProgram() {
return builderProgram;
}
function getCurrentProgram() {
- return builderProgram && builderProgram.getProgram();
+ return builderProgram && builderProgram.getProgramOrUndefined();
}
function synchronizeProgram() {
writeLog("Synchronizing program");
- var program = getCurrentProgram();
+ var program = getCurrentBuilderProgram();
if (hasChangedCompilerOptions) {
newLine = updateNewLine();
if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
@@ -74831,18 +76578,18 @@
}
}
else {
- createNewProgram(program, hasInvalidatedResolution);
+ createNewProgram(hasInvalidatedResolution);
}
if (host.afterProgramCreate) {
host.afterProgramCreate(builderProgram);
}
return builderProgram;
}
- function createNewProgram(program, hasInvalidatedResolution) {
+ function createNewProgram(hasInvalidatedResolution) {
writeLog("CreatingProgramWith::");
writeLog(" roots: " + JSON.stringify(rootFileNames));
writeLog(" options: " + JSON.stringify(compilerOptions));
- var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program;
+ var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
hasChangedCompilerOptions = false;
hasChangedConfigFileParsingErrors = false;
resolutionCache.startCachingPerDirectoryResolution();
@@ -74876,10 +76623,10 @@
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
}
function isFileMissingOnHost(hostSourceFile) {
- return typeof hostSourceFile === "number";
+ return typeof hostSourceFile === "boolean";
}
- function isFilePresentOnHost(hostSourceFile) {
- return !!hostSourceFile.sourceFile;
+ function isFilePresenceUnknownOnHost(hostSourceFile) {
+ return typeof hostSourceFile.version === "boolean";
}
function fileExists(fileName) {
var path = toPath(fileName);
@@ -74893,34 +76640,30 @@
if (isFileMissingOnHost(hostSourceFile)) {
return undefined;
}
- if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) {
+ if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
if (hostSourceFile) {
- if (shouldCreateNewSourceFile) {
- hostSourceFile.version++;
- }
if (sourceFile) {
hostSourceFile.sourceFile = sourceFile;
- sourceFile.version = hostSourceFile.version.toString();
+ hostSourceFile.version = sourceFile.version;
if (!hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file");
}
}
else {
- if (isFilePresentOnHost(hostSourceFile)) {
+ if (hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher.close();
}
- sourceFilesCache.set(path, hostSourceFile.version);
+ sourceFilesCache.set(path, false);
}
}
else {
if (sourceFile) {
- sourceFile.version = initialVersion.toString();
var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file");
- sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher });
+ sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
}
else {
- sourceFilesCache.set(path, initialVersion);
+ sourceFilesCache.set(path, false);
}
}
return sourceFile;
@@ -74931,20 +76674,20 @@
var hostSourceFile = sourceFilesCache.get(path);
if (hostSourceFile !== undefined) {
if (isFileMissingOnHost(hostSourceFile)) {
- sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 });
+ sourceFilesCache.set(path, { version: false });
}
else {
- hostSourceFile.version++;
+ hostSourceFile.version = false;
}
}
}
function getSourceVersion(path) {
var hostSourceFile = sourceFilesCache.get(path);
- return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString();
+ return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
}
function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
- if (hostSourceFileInfo) {
+ if (hostSourceFileInfo !== undefined) {
if (isFileMissingOnHost(hostSourceFileInfo)) {
(missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
}
@@ -75026,7 +76769,7 @@
}
function onSourceFileChange(fileName, eventKind, path) {
updateCachedSystemWithFile(fileName, path, eventKind);
- if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) {
+ if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
resolutionCache.invalidateResolutionOfFile(path);
}
resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
@@ -75066,7 +76809,7 @@
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
nextSourceFileVersion(fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) {
writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
@@ -75102,13 +76845,15 @@
UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
- UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream";
- UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate";
- UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked";
- UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream";
- UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
+ UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
+ UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
+ UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
+ UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
+ UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
+ UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
})(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
function createFileMap(toPath) {
var lookup = ts.createMap();
@@ -75155,60 +76900,6 @@
function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
}
- function getOutputDeclarationFileName(inputFileName, configFile) {
- var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, true);
- var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath);
- return ts.changeExtension(outputPath, ".d.ts");
- }
- ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
- function getOutputJSFileName(inputFileName, configFile) {
- var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, true);
- var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath);
- var newExtension = ts.fileExtensionIs(inputFileName, ".json") ? ".json" :
- ts.fileExtensionIs(inputFileName, ".tsx") && configFile.options.jsx === 1 ? ".jsx" : ".js";
- return ts.changeExtension(outputPath, newExtension);
- }
- function getOutputFileNames(inputFileName, configFile) {
- if (configFile.options.outFile || configFile.options.out || ts.fileExtensionIs(inputFileName, ".d.ts")) {
- return ts.emptyArray;
- }
- var outputs = [];
- var js = getOutputJSFileName(inputFileName, configFile);
- outputs.push(js);
- if (configFile.options.sourceMap) {
- outputs.push(js + ".map");
- }
- if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json")) {
- var dts = getOutputDeclarationFileName(inputFileName, configFile);
- outputs.push(dts);
- if (configFile.options.declarationMap) {
- outputs.push(dts + ".map");
- }
- }
- return outputs;
- }
- function getOutFileOutputs(project) {
- var out = project.options.outFile || project.options.out;
- if (!out) {
- return ts.Debug.fail("outFile must be set");
- }
- var outputs = [];
- outputs.push(out);
- if (project.options.sourceMap) {
- outputs.push(out + ".map");
- }
- if (ts.getEmitDeclarations(project.options)) {
- var dts = ts.changeExtension(out, ".d.ts");
- outputs.push(dts);
- if (project.options.declarationMap) {
- outputs.push(dts + ".map");
- }
- }
- return outputs;
- }
- function rootDirOfOptions(opts, configFileName) {
- return opts.rootDir || ts.getDirectoryPath(configFileName);
- }
function newer(date1, date2) {
return date2 > date1 ? date2 : date1;
}
@@ -75225,7 +76916,7 @@
ts.createBuilderStatusReporter = createBuilderStatusReporter;
function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
var host = ts.createProgramHost(system, createProgram);
- host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; };
+ host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
@@ -75234,14 +76925,14 @@
}
function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
host.reportErrorSummary = reportErrorSummary;
return host;
}
ts.createSolutionBuilderHost = createSolutionBuilderHost;
function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
var watchHost = ts.createWatchHost(system, reportWatchStatus);
ts.copyProperties(host, watchHost);
return host;
@@ -75270,9 +76961,8 @@
var readFileWithCache = function (f) { return host.readFile(f); };
var projectCompilerOptions = baseCompilerOptions;
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; });
- var originalGetSourceFile = compilerHost.getSourceFile;
- var computeHash = host.createHash || ts.generateDjb2Hash;
- updateGetSourceFile();
+ ts.setGetSourceFileAsHashVersioned(compilerHost, host);
+ var buildInfoChecked = createFileMap(toPath);
var builderPrograms = createFileMap(toPath);
var diagnostics = createFileMap(toPath);
var projectPendingBuild = createFileMap(toPath);
@@ -75308,6 +76998,7 @@
projectStatus.clear();
missingRoots.clear();
globalDependencyGraph = undefined;
+ buildInfoChecked.clear();
diagnostics.clear();
projectPendingBuild.clear();
projectErrorsReported.clear();
@@ -75322,29 +77013,6 @@
ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); });
ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher);
builderPrograms.clear();
- updateGetSourceFile();
- }
- function updateGetSourceFile() {
- if (options.watch) {
- if (compilerHost.getSourceFile === originalGetSourceFile) {
- compilerHost.getSourceFile = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
- if (result && options.watch) {
- result.version = computeHash.call(host, result.text);
- }
- return result;
- };
- }
- }
- else {
- if (compilerHost.getSourceFile !== originalGetSourceFile) {
- compilerHost.getSourceFile = originalGetSourceFile;
- }
- }
}
function isParsedCommandLine(entry) {
return !!entry.options;
@@ -75487,12 +77155,12 @@
newestInputFileTime = inputTime;
}
}
- var outputs = getAllProjectOutputs(project);
- if (outputs.length === 0) {
+ if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) {
return {
type: UpToDateStatusType.ContainerOnly
};
}
+ var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
var oldestOutputFileName = "(none)";
var oldestOutputFileTime = maximumDate;
var newestOutputFileName = "(none)";
@@ -75555,6 +77223,7 @@
upstreamProjectName: ref.path
};
}
+ if (!missingOutputFileName) {
if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
continue;
}
@@ -75571,6 +77240,7 @@
};
}
}
+ }
if (missingOutputFileName !== undefined) {
return {
type: UpToDateStatusType.OutputMissing,
@@ -75584,9 +77254,31 @@
newerInputFileName: newestInputFileName
};
}
+ else {
+ var configStatus = checkConfigFileUpToDateStatus(project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
+ if (configStatus)
+ return configStatus;
+ var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName); });
+ if (extendedConfigStatus)
+ return extendedConfigStatus;
+ }
+ if (!buildInfoChecked.hasKey(project.options.configFilePath)) {
+ buildInfoChecked.setValue(project.options.configFilePath, true);
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath) {
+ var value = readFileWithCache(buildInfoPath);
+ var buildInfo = value && ts.getBuildInfo(value);
+ if (buildInfo && buildInfo.version !== ts.version) {
+ return {
+ type: UpToDateStatusType.TsVersionOutputOfDate,
+ version: buildInfo.version
+ };
+ }
+ }
+ }
if (usesPrepend && pseudoUpToDate) {
return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
+ type: UpToDateStatusType.OutOfDateWithPrepend,
outOfDateOutputFileName: oldestOutputFileName,
newerProjectName: upstreamChangedProject
};
@@ -75601,6 +77293,16 @@
oldestOutputFileName: oldestOutputFileName
};
}
+ function checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName) {
+ var tsconfigTime = host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
+ if (oldestOutputFileTime < tsconfigTime) {
+ return {
+ type: UpToDateStatusType.OutOfDateWithSelf,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerInputFileName: configFile
+ };
+ }
+ }
function invalidateProject(configFileName, reloadLevel) {
invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel);
}
@@ -75713,7 +77415,9 @@
updateOutputTimestamps(proj);
return;
}
- var buildResult = buildSingleProject(resolved);
+ var buildResult = needsBuild(status, resolved) ?
+ buildSingleProject(resolved) :
+ updateBundle(resolved);
if (buildResult & BuildResultFlags.AnyErrors)
return;
var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue;
@@ -75725,18 +77429,27 @@
var prepend = referencingProjects.getValue(project);
if (prepend !== undefined) {
var status_1 = projectStatus.getValue(project);
- if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
- if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) {
+ if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
+ if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status_1.type === UpToDateStatusType.OutOfDateWithPrepend)) {
projectStatus.setValue(project, {
type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: status_1.oldestOutputFileName,
+ outOfDateOutputFileName: status_1.type === UpToDateStatusType.OutOfDateWithPrepend ? status_1.outOfDateOutputFileName : status_1.oldestOutputFileName,
newerProjectName: resolved
});
}
}
else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) {
+ if (prepend) {
+ projectStatus.setValue(project, {
+ type: UpToDateStatusType.OutOfDateWithPrepend,
+ outOfDateOutputFileName: status_1.oldestOutputFileName,
+ newerProjectName: resolved
+ });
+ }
+ else {
status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
}
+ }
addProjToQueue(project);
}
}
@@ -75788,8 +77501,7 @@
}
if (options.verbose)
reportStatus(ts.Diagnostics.Building_project_0, proj);
- var resultFlags = BuildResultFlags.None;
- resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
+ var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
var configFile = parseConfigFile(proj);
if (!configFile) {
resultFlags |= BuildResultFlags.ConfigFileErrors;
@@ -75802,8 +77514,7 @@
return BuildResultFlags.None;
}
projectCompilerOptions = configFile.options;
- var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences);
- projectCompilerOptions = baseCompilerOptions;
+ var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, getOldProgram(proj, configFile), configFile.errors, configFile.projectReferences);
var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic");
@@ -75852,17 +77563,19 @@
var status = {
type: UpToDateStatusType.UpToDate,
newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime,
- oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile)
+ oldestOutputFileName: outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(configFile, !host.useCaseSensitiveFileNames())
};
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
}
}
@@ -75875,15 +77588,68 @@
builderPrograms.setValue(proj, program);
}
}
+ function getOldProgram(proj, parsed) {
+ if (options.force)
+ return undefined;
+ var value = builderPrograms.getValue(proj);
+ if (value)
+ return value;
+ return ts.readBuilderProgram(parsed.options, readFileWithCache);
+ }
+ function updateBundle(proj) {
+ if (options.dry) {
+ reportStatus(ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
+ return BuildResultFlags.Success;
+ }
+ if (options.verbose)
+ reportStatus(ts.Diagnostics.Updating_output_of_project_0, proj);
+ var config = ts.Debug.assertDefined(parseConfigFile(proj));
+ projectCompilerOptions = config.options;
+ var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) { return parseConfigFile(resolveProjectName(ref.path)); });
+ if (ts.isString(outputFiles)) {
+ reportStatus(ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
+ return buildSingleProject(proj);
+ }
+ ts.Debug.assert(!!outputFiles.length);
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ var emittedOutputs = createFileMap(toPath);
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
+ emittedOutputs.setValue(name, true);
+ ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
+ });
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
+ reportAndStoreErrors(proj, emitDiagnostics);
+ projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
+ }
+ var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
+ oldestOutputFileName: outputFiles[0].name
+ };
+ diagnostics.removeKey(proj);
+ projectStatus.setValue(proj, status);
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged;
+ }
function updateOutputTimestamps(proj) {
if (options.dry) {
- return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
+ return reportStatus(ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
}
var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
- projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
+ oldestOutputFileName: ts.getFirstProjectOutput(proj, !host.useCaseSensitiveFileNames())
+ };
+ projectStatus.setValue(proj.options.configFilePath, status);
}
function updateOutputTimestampsWorker(proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
- var outputs = getAllProjectOutputs(proj);
+ var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
if (!skipOutputs || outputs.length !== skipOutputs.getSize()) {
if (options.verbose) {
reportStatus(verboseMessage, proj.options.configFilePath);
@@ -75915,7 +77681,7 @@
reportParseConfigFileDiagnostic(proj);
continue;
}
- var outputs = getAllProjectOutputs(parsed);
+ var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) {
var output = outputs_3[_b];
if (host.fileExists(output)) {
@@ -75995,7 +77761,9 @@
reportAndStoreErrors(next, errors);
continue;
}
- var buildResult = buildSingleProject(next);
+ var buildResult = needsBuild(status, next) ?
+ buildSingleProject(next) :
+ updateBundle(next);
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
@@ -76008,6 +77776,15 @@
readFileWithCache = savedReadFileWithCache;
return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
}
+ function needsBuild(status, configFile) {
+ if (status.type !== UpToDateStatusType.OutOfDateWithPrepend || options.force)
+ return true;
+ var config = parseConfigFile(configFile);
+ return !config ||
+ config.fileNames.length === 0 ||
+ !!config.errors.length ||
+ !ts.isIncrementalCompilation(config.options);
+ }
function reportParseConfigFileDiagnostic(proj) {
reportAndStoreErrors(proj, [configFileCache.getValue(proj)]);
}
@@ -76041,33 +77818,6 @@
return ts.combinePaths(project, "tsconfig.json");
}
ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
- function getAllProjectOutputs(project) {
- if (project.options.outFile || project.options.out) {
- 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 getFirstProjectOutput(project) {
- if (project.options.outFile || project.options.out) {
- return ts.first(getOutFileOutputs(project));
- }
- for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
- var inputFile = _a[_i];
- var outputs = getOutputFileNames(inputFile, project);
- if (outputs.length) {
- return ts.first(outputs);
- }
- }
- return ts.Debug.fail("project " + project.options.configFilePath + " expected to have at least one output");
- }
function formatUpToDateStatus(configFileName, status, relName, formatMessage) {
switch (status.type) {
case UpToDateStatusType.OutOfDateWithSelf:
@@ -76081,6 +77831,8 @@
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 || ""));
}
break;
+ case UpToDateStatusType.OutOfDateWithPrepend:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(configFileName), relName(status.newerProjectName));
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:
@@ -76089,6 +77841,8 @@
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.TsVersionOutputOfDate:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(configFileName), status.version, ts.version);
case UpToDateStatusType.ContainerOnly:
case UpToDateStatusType.ComputingUpstream:
break;
@@ -76225,7 +77979,6 @@
}
}
})(ts || (ts = {}));
-//# sourceMappingURL=compiler.release.js.map
var ts;
(function (ts) {
function countLines(program) {
@@ -76352,6 +78105,9 @@
reportWatchModeWithoutSysSupport();
createWatchOfConfigFile(configParseResult, commandLineOptions);
}
+ else if (ts.isIncrementalCompilation(configParseResult.options)) {
+ performIncrementalCompilation(configParseResult);
+ }
else {
performCompilation(configParseResult.fileNames, configParseResult.projectReferences, configParseResult.options, ts.getConfigFileParsingDiagnostics(configParseResult));
}
@@ -76391,7 +78147,7 @@
return ts.sys.exit(ts.ExitStatus.Success);
}
// Update to pretty if host supports it
- updateReportDiagnostic();
+ updateReportDiagnostic(buildOptions);
if (projects.length === 0) {
ts.printVersion();
ts.printHelp(ts.buildOpts, "--build ");
@@ -76404,9 +78160,10 @@
if (buildOptions.watch) {
reportWatchModeWithoutSysSupport();
}
+ // Use default createProgram
var buildHost = buildOptions.watch ?
- ts.createSolutionBuilderWithWatchHost(ts.sys, ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createWatchStatusReporter()) :
- ts.createSolutionBuilderHost(ts.sys, ts.createAbstractBuilder, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createReportErrorSummary(buildOptions));
+ ts.createSolutionBuilderWithWatchHost(ts.sys, /*createProgram*/ undefined, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty(buildOptions)), createWatchStatusReporter(buildOptions)) :
+ ts.createSolutionBuilderHost(ts.sys, /*createProgram*/ undefined, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty(buildOptions)), createReportErrorSummary(buildOptions));
updateCreateProgram(buildHost);
buildHost.afterProgramEmitAndDiagnostics = function (program) { return reportStatistics(program.getProgram()); };
var builder = ts.createSolutionBuilder(buildHost, projects, buildOptions);
@@ -76442,6 +78199,19 @@
reportStatistics(program);
return ts.sys.exit(exitStatus);
}
+ function performIncrementalCompilation(config) {
+ var options = config.options, fileNames = config.fileNames, projectReferences = config.projectReferences;
+ enableStatistics(options);
+ return ts.sys.exit(ts.performIncrementalCompilation({
+ rootNames: fileNames,
+ options: options,
+ configFileParsingDiagnostics: ts.getConfigFileParsingDiagnostics(config),
+ projectReferences: projectReferences,
+ reportDiagnostic: reportDiagnostic,
+ reportErrorSummary: createReportErrorSummary(options),
+ afterProgramEmitAndDiagnostics: function (builderProgram) { return reportStatistics(builderProgram.getProgram()); }
+ }));
+ }
function updateCreateProgram(host) {
var compileUsingBuilder = host.createProgram;
host.createProgram = function (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) {

lib/tsserver.js

@@ -15,31 +15,6 @@
"use strict";
-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 __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];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
@@ -82,13 +57,35 @@
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 __rest = (this && this.__rest) || function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
+ t[p[i]] = s[p[i]];
+ return t;
+};
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.3";
+ ts.versionMajorMinor = "3.4";
/** The version of the TypeScript compiler release */
- ts.version = ts.versionMajorMinor + ".4000";
+ ts.version = ts.versionMajorMinor + ".5";
})(ts || (ts = {}));
(function (ts) {
/* @internal */
@@ -144,19 +141,25 @@
// Keep the class inside a function so it doesn't get compiled if it's not used.
function shimMap() {
var MapIterator = /** @class */ (function () {
- function MapIterator(data, selector) {
- this.index = 0;
- this.data = data;
+ function MapIterator(currentEntry, selector) {
+ this.currentEntry = currentEntry;
this.selector = selector;
- this.keys = Object.keys(data);
}
MapIterator.prototype.next = function () {
- var index = this.index;
- if (index < this.keys.length) {
- this.index++;
- return { value: this.selector(this.data, this.keys[index]), done: false };
+ // Navigate to the next entry.
+ while (this.currentEntry) {
+ var skipNext = !!this.currentEntry.skipNext;
+ this.currentEntry = this.currentEntry.nextEntry;
+ if (!skipNext) {
+ break;
}
+ }
+ if (this.currentEntry) {
+ return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false };
+ }
+ else {
return { value: undefined, done: true };
+ }
};
return MapIterator;
}());
@@ -164,15 +167,36 @@
function class_1() {
this.data = createDictionaryObject();
this.size = 0;
+ // Create a first (stub) map entry that will not contain a key
+ // and value but serves as starting point for iterators.
+ this.firstEntry = {};
+ // When the map is empty, the last entry is the same as the
+ // first one.
+ this.lastEntry = this.firstEntry;
}
class_1.prototype.get = function (key) {
- return this.data[key];
+ var entry = this.data[key];
+ return entry && entry.value;
};
class_1.prototype.set = function (key, value) {
if (!this.has(key)) {
this.size++;
+ // Create a new entry that will be appended at the
+ // end of the linked list.
+ var newEntry = {
+ key: key,
+ value: value
+ };
+ this.data[key] = newEntry;
+ // Adjust the references.
+ var previousLastEntry = this.lastEntry;
+ previousLastEntry.nextEntry = newEntry;
+ newEntry.previousEntry = previousLastEntry;
+ this.lastEntry = newEntry;
+ }
+ else {
+ this.data[key].value = value;
}
- this.data[key] = value;
return this;
};
class_1.prototype.has = function (key) {
@@ -182,7 +206,28 @@
class_1.prototype.delete = function (key) {
if (this.has(key)) {
this.size--;
+ var entry = this.data[key];
delete this.data[key];
+ // Adjust the linked list references of the neighbor entries.
+ var previousEntry = entry.previousEntry;
+ previousEntry.nextEntry = entry.nextEntry;
+ if (entry.nextEntry) {
+ entry.nextEntry.previousEntry = previousEntry;
+ }
+ // When the deleted entry was the last one, we need to
+ // adust the lastEntry reference.
+ if (this.lastEntry === entry) {
+ this.lastEntry = previousEntry;
+ }
+ // Adjust the forward reference of the deleted entry
+ // in case an iterator still references it. This allows us
+ // to throw away the entry, but when an active iterator
+ // (which points to the current entry) continues, it will
+ // navigate to the entry that originally came before the
+ // current one and skip it.
+ entry.previousEntry = undefined;
+ entry.nextEntry = previousEntry;
+ entry.skipNext = true;
return true;
}
return false;
@@ -190,24 +235,46 @@
class_1.prototype.clear = function () {
this.data = createDictionaryObject();
this.size = 0;
+ // Reset the linked list. Note that we must adjust the forward
+ // references of the deleted entries to ensure iterators stuck
+ // in the middle of the list don't continue with deleted entries,
+ // but can continue with new entries added after the clear()
+ // operation.
+ var firstEntry = this.firstEntry;
+ var currentEntry = firstEntry.nextEntry;
+ while (currentEntry) {
+ var nextEntry = currentEntry.nextEntry;
+ currentEntry.previousEntry = undefined;
+ currentEntry.nextEntry = firstEntry;
+ currentEntry.skipNext = true;
+ currentEntry = nextEntry;
+ }
+ firstEntry.nextEntry = undefined;
+ this.lastEntry = firstEntry;
};
class_1.prototype.keys = function () {
- return new MapIterator(this.data, function (_data, key) { return key; });
+ return new MapIterator(this.firstEntry, function (key) { return key; });
};
class_1.prototype.values = function () {
- return new MapIterator(this.data, function (data, key) { return data[key]; });
+ return new MapIterator(this.firstEntry, function (_key, value) { return value; });
};
class_1.prototype.entries = function () {
- return new MapIterator(this.data, function (data, key) { return [key, data[key]]; });
+ return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; });
};
class_1.prototype.forEach = function (action) {
- for (var key in this.data) {
- action(this.data[key], key);
+ var iterator = this.entries();
+ while (true) {
+ var _a = iterator.next(), entry = _a.value, done = _a.done;
+ if (done) {
+ break;
+ }
+ action(entry[1], entry[0]);
}
};
return class_1;
}());
}
+ ts.shimMap = shimMap;
function length(array) {
return array ? array.length : 0;
}
@@ -755,7 +822,7 @@
}
/**
* Deduplicates an unsorted array.
- * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates.
+ * @param equalityComparer An `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`.
*/
@@ -971,6 +1038,21 @@
} };
}
ts.arrayIterator = arrayIterator;
+ function arrayReverseIterator(array) {
+ var i = array.length;
+ return {
+ next: function () {
+ if (i === 0) {
+ return { value: undefined, done: true };
+ }
+ else {
+ i--;
+ return { value: array[i], done: false };
+ }
+ }
+ };
+ }
+ ts.arrayReverseIterator = arrayReverseIterator;
/**
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
*/
@@ -1181,9 +1263,11 @@
}
for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
var arg = args_1[_a];
+ if (arg === undefined)
+ continue;
for (var p in arg) {
if (hasProperty(arg, p)) {
- t[p] = arg[p]; // TODO: GH#23368
+ t[p] = arg[p];
}
}
}
@@ -1359,6 +1443,9 @@
/** Do nothing and return true */
function returnTrue() { return true; }
ts.returnTrue = returnTrue;
+ /** Do nothing and return undefined */
+ function returnUndefined() { return undefined; }
+ ts.returnUndefined = returnUndefined;
/** Returns its argument. */
function identity(x) { return x; }
ts.identity = identity;
@@ -1505,7 +1592,7 @@
Debug.assertEachDefined = assertEachDefined;
function assertNever(member, message, stackCrawlMark) {
if (message === void 0) { message = "Illegal value:"; }
- var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member);
+ var detail = typeof member === "object" && "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member);
return fail(message + " " + detail, stackCrawlMark || assertNever);
}
Debug.assertNever = assertNever;
@@ -2808,47 +2895,53 @@
SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment";
// Enum
SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember";
+ // Unparsed
+ SyntaxKind[SyntaxKind["UnparsedPrologue"] = 279] = "UnparsedPrologue";
+ SyntaxKind[SyntaxKind["UnparsedPrepend"] = 280] = "UnparsedPrepend";
+ SyntaxKind[SyntaxKind["UnparsedText"] = 281] = "UnparsedText";
+ SyntaxKind[SyntaxKind["UnparsedInternalText"] = 282] = "UnparsedInternalText";
+ SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 283] = "UnparsedSyntheticReference";
// Top-level nodes
- SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile";
- SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle";
- SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource";
- SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles";
+ SyntaxKind[SyntaxKind["SourceFile"] = 284] = "SourceFile";
+ SyntaxKind[SyntaxKind["Bundle"] = 285] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 286] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 287] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 288] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 289] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature";
- SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag";
- SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 290] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 291] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 292] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 293] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 294] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 295] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 296] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 297] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocSignature"] = 298] = "JSDocSignature";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 299] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 300] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 301] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 302] = "JSDocCallbackTag";
+ SyntaxKind[SyntaxKind["JSDocEnumTag"] = 303] = "JSDocEnumTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 304] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 305] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocThisTag"] = 306] = "JSDocThisTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 307] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 308] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 309] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 310] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 311] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 312] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 313] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 314] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 315] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 316] = "EndOfDeclarationMarker";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 312] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 317] = "Count";
// Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment";
@@ -2875,10 +2968,10 @@
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator";
SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 288] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 310] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 299] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 310] = "LastJSDocTagNode";
/* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword";
/* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
@@ -2985,21 +3078,27 @@
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
})(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
- /* @internal */
var TokenFlags;
(function (TokenFlags) {
TokenFlags[TokenFlags["None"] = 0] = "None";
+ /* @internal */
TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
+ /* @internal */
TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
+ /* @internal */
TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
+ /* @internal */
TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
+ /* @internal */
TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
+ /* @internal */
TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
+ /* @internal */
TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
})(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
var FlowFlags;
@@ -3359,12 +3458,6 @@
TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
/* @internal */
- TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType";
- /* @internal */
- TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral";
- /* @internal */
- TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType";
- /* @internal */
TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
/* @internal */
TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
@@ -3396,28 +3489,29 @@
TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive";
TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable";
TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable";
+ /* @internal */
+ TypeFlags[TypeFlags["ObjectFlagsType"] = 3899392] = "ObjectFlagsType";
// 'Narrowable' types are types where narrowing actually narrows.
// This *should* be every type other than null, undefined, void, and never
TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable";
TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit";
/* @internal */
TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion";
+ // The following flags are aggregated during union and intersection type construction
/* @internal */
- TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening";
- /* @internal */
- TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags";
+ TypeFlags[TypeFlags["IncludesMask"] = 1835007] = "IncludesMask";
// The following flags are used for different purposes during union and intersection type construction
/* @internal */
- TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType";
+ TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
/* @internal */
- TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard";
+ TypeFlags[TypeFlags["IncludesNonWideningType"] = 2097152] = "IncludesNonWideningType";
/* @internal */
- TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject";
+ TypeFlags[TypeFlags["IncludesWildcard"] = 4194304] = "IncludesWildcard";
/* @internal */
- TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags";
+ TypeFlags[TypeFlags["IncludesEmptyObject"] = 8388608] = "IncludesEmptyObject";
// The following flag is used for different purposes by maybeTypeOfKind
/* @internal */
- TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType";
+ TypeFlags[TypeFlags["GenericMappedType"] = 131072] = "GenericMappedType";
})(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
var ObjectFlags;
(function (ObjectFlags) {
@@ -3437,7 +3531,19 @@
ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
+ /* @internal */
+ ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion";
+ /* @internal */
+ ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType";
+ /* @internal */
+ ObjectFlags[ObjectFlags["ContainsObjectLiteral"] = 262144] = "ContainsObjectLiteral";
+ /* @internal */
+ ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType";
ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
+ /* @internal */
+ ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening";
+ /* @internal */
+ ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags";
})(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
/* @internal */
var Variance;
@@ -3482,6 +3588,7 @@
InferenceFlags[InferenceFlags["None"] = 0] = "None";
InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
+ InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
})(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
/**
* Ternary values are defined such that
@@ -3589,9 +3696,10 @@
ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
- ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext";
+ ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
+ ScriptTarget[ScriptTarget["ESNext"] = 7] = "ESNext";
ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
- ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest";
+ ScriptTarget[ScriptTarget["Latest"] = 7] = "Latest";
})(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
var LanguageVariant;
(function (LanguageVariant) {
@@ -3740,6 +3848,7 @@
Extension["Js"] = ".js";
Extension["Jsx"] = ".jsx";
Extension["Json"] = ".json";
+ Extension["TsBuildInfo"] = ".tsbuildinfo";
})(Extension = ts.Extension || (ts.Extension = {}));
/* @internal */
var TransformFlags;
@@ -3747,71 +3856,69 @@
TransformFlags[TransformFlags["None"] = 0] = "None";
// Facts
// - Flags used to indicate that a node or subtree contains syntax that requires transformation.
- TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript";
- TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript";
- TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx";
- TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext";
- TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017";
- TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016";
- TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015";
+ TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
+ TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
+ TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
+ TransformFlags[TransformFlags["ContainsES2019"] = 8] = "ContainsES2019";
+ TransformFlags[TransformFlags["ContainsES2018"] = 16] = "ContainsES2018";
+ TransformFlags[TransformFlags["ContainsES2017"] = 32] = "ContainsES2017";
+ TransformFlags[TransformFlags["ContainsES2016"] = 64] = "ContainsES2016";
TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015";
- TransformFlags[TransformFlags["Generator"] = 256] = "Generator";
- TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
- TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment";
- TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment";
+ TransformFlags[TransformFlags["ContainsGenerator"] = 256] = "ContainsGenerator";
+ TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 512] = "ContainsDestructuringAssignment";
// Markers
// - Flags used to indicate that a subtree contains a specific transformation.
- TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax";
- TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis";
- TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis";
- TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName";
- TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments";
- TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread";
- TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread";
- TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName";
- TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding";
- TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern";
- TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield";
- TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion";
- TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport";
- TransformFlags[TransformFlags["Super"] = 33554432] = "Super";
- TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper";
+ TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 1024] = "ContainsTypeScriptClassSyntax";
+ TransformFlags[TransformFlags["ContainsLexicalThis"] = 2048] = "ContainsLexicalThis";
+ TransformFlags[TransformFlags["ContainsRestOrSpread"] = 4096] = "ContainsRestOrSpread";
+ TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 8192] = "ContainsObjectRestOrSpread";
+ TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 16384] = "ContainsComputedPropertyName";
+ TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 32768] = "ContainsBlockScopedBinding";
+ TransformFlags[TransformFlags["ContainsBindingPattern"] = 65536] = "ContainsBindingPattern";
+ TransformFlags[TransformFlags["ContainsYield"] = 131072] = "ContainsYield";
+ TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 262144] = "ContainsHoistedDeclarationOrCompletion";
+ TransformFlags[TransformFlags["ContainsDynamicImport"] = 524288] = "ContainsDynamicImport";
// Please leave this as 1 << 29.
// It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
// It is a good reminder of how much room we have left
TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
// Assertions
// - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
- TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript";
- TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx";
- TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext";
- TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017";
- TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016";
- TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015";
- TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator";
- TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment";
+ TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
+ TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
+ TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
+ TransformFlags[TransformFlags["AssertES2019"] = 8] = "AssertES2019";
+ TransformFlags[TransformFlags["AssertES2018"] = 16] = "AssertES2018";
+ TransformFlags[TransformFlags["AssertES2017"] = 32] = "AssertES2017";
+ TransformFlags[TransformFlags["AssertES2016"] = 64] = "AssertES2016";
+ TransformFlags[TransformFlags["AssertES2015"] = 128] = "AssertES2015";
+ TransformFlags[TransformFlags["AssertGenerator"] = 256] = "AssertGenerator";
+ TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 512] = "AssertDestructuringAssignment";
// Scope Exclusions
// - Bitmasks that exclude flags from propagating out of a specific context
// into the subtree flags of their container.
- TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes";
- TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes";
- TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes";
- TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes";
- TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes";
- TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes";
- TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes";
- TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes";
- TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes";
- TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes";
- TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes";
- TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes";
- TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes";
- TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes";
- TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes";
- TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes";
+ TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
+ TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
+ TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
+ TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 537371648] = "ArrowFunctionExcludes";
+ TransformFlags[TransformFlags["FunctionExcludes"] = 537373696] = "FunctionExcludes";
+ TransformFlags[TransformFlags["ConstructorExcludes"] = 537372672] = "ConstructorExcludes";
+ TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 537372672] = "MethodOrAccessorExcludes";
+ TransformFlags[TransformFlags["PropertyExcludes"] = 536872960] = "PropertyExcludes";
+ TransformFlags[TransformFlags["ClassExcludes"] = 536888320] = "ClassExcludes";
+ TransformFlags[TransformFlags["ModuleExcludes"] = 537168896] = "ModuleExcludes";
+ TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
+ TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536896512] = "ObjectLiteralExcludes";
+ TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536875008] = "ArrayLiteralOrCallOrNewExcludes";
+ TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 536944640] = "VariableDeclarationListExcludes";
+ TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
+ TransformFlags[TransformFlags["CatchClauseExcludes"] = 536879104] = "CatchClauseExcludes";
+ TransformFlags[TransformFlags["BindingPatternExcludes"] = 536875008] = "BindingPatternExcludes";
+ // Propagating flags
+ // - Bitmasks for flags that should propagate from a child
+ TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 2048] = "PropertyNamePropagatingFlags";
// Masks
// - Additional bitmasks
- TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask";
})(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
var EmitFlags;
(function (EmitFlags) {
@@ -3893,6 +4000,20 @@
EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
})(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
+ /*@internal*/
+ var BundleFileSectionKind;
+ (function (BundleFileSectionKind) {
+ BundleFileSectionKind["Prologue"] = "prologue";
+ BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
+ BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
+ BundleFileSectionKind["Reference"] = "reference";
+ BundleFileSectionKind["Type"] = "type";
+ BundleFileSectionKind["Lib"] = "lib";
+ BundleFileSectionKind["Prepend"] = "prepend";
+ BundleFileSectionKind["Text"] = "text";
+ BundleFileSectionKind["Internal"] = "internal";
+ // comments?
+ })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
var ListFormat;
(function (ListFormat) {
ListFormat[ListFormat["None"] = 0] = "None";
@@ -4039,8 +4160,11 @@
*/
/* @internal */
function generateDjb2Hash(data) {
- var chars = data.split("").map(function (str) { return str.charCodeAt(0); });
- return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381);
+ var acc = 5381;
+ for (var i = 0; i < data.length; i++) {
+ acc = ((acc << 5) + acc) + data.charCodeAt(i);
+ }
+ return acc.toString();
}
ts.generateDjb2Hash = generateDjb2Hash;
/**
@@ -4300,6 +4424,8 @@
: FileWatcherEventKind.Changed;
}
ts.getFileWatcherEventKind = getFileWatcherEventKind;
+ /*@internal*/
+ ts.ignoredPaths = ["/node_modules/.", "/.git"];
/**
* 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
@@ -4324,6 +4450,8 @@
else {
directoryWatcher = {
watcher: host.watchDirectory(dirName, function (fileName) {
+ if (isIgnoredPath(fileName))
+ return;
// Call the actual callback
callbackCache.forEach(function (callbacks, rootDirName) {
if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
@@ -4373,7 +4501,7 @@
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 filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
+ return !isIgnoredPath(childFullName) && 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;
/**
@@ -4390,6 +4518,16 @@
(newChildWatches || (newChildWatches = [])).push(childWatcher);
}
}
+ function isIgnoredPath(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
+ }
+ function isInPath(path, searchPath) {
+ if (ts.stringContains(path, searchPath))
+ return true;
+ if (host.useCaseSensitiveFileNames)
+ return false;
+ return ts.stringContains(toCanonicalFilePath(path), searchPath);
+ }
}
ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher;
function getNodeMajorVersion() {
@@ -4458,8 +4596,18 @@
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!nodeSystem.directoryExists(directoryName)) {
+ // Wrapped in a try-catch to prevent crashing if we are in a race
+ // with another copy of ourselves to create the same directory
+ try {
_fs.mkdirSync(directoryName);
}
+ catch (e) {
+ if (e.code !== "EEXIST") {
+ // Failed for some other reason (access denied?); still throw
+ throw e;
+ }
+ }
+ }
},
getExecutingFilePath: function () {
return __filename;
@@ -4475,7 +4623,7 @@
getModifiedTime: getModifiedTime,
setModifiedTime: setModifiedTime,
deleteFile: deleteFile,
- createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash,
+ createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
createSHA256Hash: _crypto ? createSHA256Hash : undefined,
getMemoryUsage: function () {
if (global.gc) {
@@ -4863,7 +5011,7 @@
}
}
function readDirectory(path, extensions, excludes, includes, depth) {
- return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries);
+ return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
}
function fileSystemEntryExists(path, entryKind) {
try {
@@ -4919,11 +5067,6 @@
return;
}
}
- function createMD5HashUsingNativeCrypto(data) {
- var hash = _crypto.createHash("md5");
- hash.update(data);
- return hash.digest("hex");
- }
function createSHA256Hash(data) {
var hash = _crypto.createHash("sha256");
hash.update(data);
@@ -5184,7 +5327,6 @@
Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."),
Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."),
- Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."),
Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."),
A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."),
Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."),
@@ -5275,6 +5417,8 @@
An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."),
A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."),
A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."),
+ readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types: diag(1354, ts.DiagnosticCategory.Error, "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354", "'readonly' type modifier is only permitted on array and tuple literal types."),
+ A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal: diag(1355, ts.DiagnosticCategory.Error, "A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal_1355", "A 'const' assertion can only be applied to a string, number, boolean, array, or object literal."),
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."),
@@ -5369,7 +5513,7 @@
Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."),
Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
- Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."),
+ This_overload_signature_is_not_compatible_with_its_implementation_signature: diag(2394, ts.DiagnosticCategory.Error, "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394", "This overload signature is not compatible with its implementation signature."),
Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."),
Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."),
Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."),
@@ -5542,15 +5686,20 @@
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."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."),
Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."),
_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
+ Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."),
+ Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
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."),
@@ -5657,6 +5806,12 @@
This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."),
This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."),
_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."),
+ Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided: diag(2748, ts.DiagnosticCategory.Error, "Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided_2748", "Cannot access ambient const enums when the '--isolatedModules' flag is provided."),
+ _0_refers_to_a_value_but_is_being_used_as_a_type_here: diag(2749, ts.DiagnosticCategory.Error, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_2749", "'{0}' refers to a value, but is being used as a type here."),
+ The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
+ Circularity_originates_in_type_at_this_location: diag(2751, ts.DiagnosticCategory.Error, "Circularity_originates_in_type_at_this_location_2751", "Circularity originates in type at this location."),
+ The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
+ Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
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}'."),
@@ -5740,6 +5895,7 @@
Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
@@ -5788,7 +5944,7 @@
Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."),
Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
- Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."),
+ Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'."),
Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."),
Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
@@ -6007,6 +6163,16 @@
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."),
Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
+ Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
+ Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
+ A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
+ A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
+ Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
+ Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
+ Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
+ Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
+ Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
+ Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
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."),
The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
@@ -6043,7 +6209,7 @@
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'."),
+ The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."),
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."),
Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
@@ -6223,6 +6389,7 @@
Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
+ Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
};
})(ts || (ts = {}));
var ts;
@@ -6710,16 +6877,20 @@
return pos;
}
var shebangTriviaRegex = /^#!.*/;
+ /*@internal*/
function isShebangTrivia(text, pos) {
// Shebangs check must only be done at the start of the file
ts.Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
+ ts.isShebangTrivia = isShebangTrivia;
+ /*@internal*/
function scanShebangTrivia(text, pos) {
var shebang = shebangTriviaRegex.exec(text)[0];
pos = pos + shebang.length;
return pos;
}
+ ts.scanShebangTrivia = scanShebangTrivia;
/**
* Invokes a callback for each comment range following the provided position.
*
@@ -6746,8 +6917,15 @@
var pendingKind;
var pendingHasTrailingNewLine;
var hasPendingCommentRange = false;
- var collecting = trailing || pos === 0;
+ var collecting = trailing;
var accumulator = initial;
+ if (pos === 0) {
+ collecting = true;
+ var shebang = getShebang(text);
+ if (shebang) {
+ pos = shebang.length;
+ }
+ }
scan: while (pos >= 0 && pos < text.length) {
var ch = text.charCodeAt(pos);
switch (ch) {
@@ -7982,6 +8160,7 @@
}
pos++;
}
+ tokenValue = text.substring(startPos, pos);
return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
}
// Scans a JSX identifier; these differ from normal identifiers in that
@@ -8063,8 +8242,8 @@
pos++;
return token = 14 /* NoSubstitutionTemplateLiteral */;
}
- if (isIdentifierStart(ch, 6 /* Latest */)) {
- while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) {
+ if (isIdentifierStart(ch, 7 /* Latest */)) {
+ while (isIdentifierPart(text.charCodeAt(pos), 7 /* Latest */) && pos < end) {
pos++;
}
tokenValue = text.substring(tokenPos, pos);
@@ -8422,7 +8601,7 @@
}
}
function getSourceFileOfNode(node) {
- while (node && node.kind !== 279 /* SourceFile */) {
+ while (node && node.kind !== 284 /* SourceFile */) {
node = node.parent;
}
return node;
@@ -8509,10 +8688,7 @@
return !nodeIsMissing(node);
}
ts.nodeIsPresent = nodeIsPresent;
- /**
- * Prepends statements to an array while taking care of prologue directives.
- */
- function addStatementsAfterPrologue(to, from) {
+ function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
if (from === undefined || from.length === 0)
return to;
var statementIndex = 0;
@@ -8525,7 +8701,44 @@
to.splice.apply(to, [statementIndex, 0].concat(from));
return to;
}
- ts.addStatementsAfterPrologue = addStatementsAfterPrologue;
+ function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
+ if (statement === undefined)
+ return to;
+ 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(statementIndex, 0, statement);
+ return to;
+ }
+ function isAnyPrologueDirective(node) {
+ return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
+ }
+ /**
+ * Prepends statements to an array while taking care of prologue directives.
+ */
+ function insertStatementsAfterStandardPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isPrologueDirective);
+ }
+ ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
+ function insertStatementsAfterCustomPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
+ }
+ ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
+ /**
+ * Prepends statements to an array while taking care of prologue directives.
+ */
+ function insertStatementAfterStandardPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isPrologueDirective);
+ }
+ ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
+ function insertStatementAfterCustomPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
+ }
+ ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
/**
* Determine if the given comment is a triple-slash
*
@@ -8568,7 +8781,7 @@
// 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 === 306 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 311 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -8587,7 +8800,7 @@
}
ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
function isJSDocTypeExpressionOrChild(node) {
- return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
+ return node.kind === 288 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
}
function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
@@ -8714,7 +8927,7 @@
return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body);
}
function isBlockScopedContainerTopLevel(node) {
- return node.kind === 279 /* SourceFile */ ||
+ return node.kind === 284 /* SourceFile */ ||
node.kind === 244 /* ModuleDeclaration */ ||
ts.isFunctionLike(node);
}
@@ -8732,7 +8945,7 @@
// - 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 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node.parent);
case 245 /* ModuleBlock */:
return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
@@ -8750,7 +8963,7 @@
ts.isEffectiveExternalModule = isEffectiveExternalModule;
function isBlockScope(node, parentNode) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 274 /* CatchClause */:
case 244 /* ModuleDeclaration */:
@@ -8775,9 +8988,9 @@
ts.isBlockScope = isBlockScope;
function isDeclarationWithTypeParameters(node) {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
- case 293 /* JSDocSignature */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 298 /* JSDocSignature */:
return true;
default:
ts.assertType(node);
@@ -8793,12 +9006,12 @@
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
@@ -8943,7 +9156,7 @@
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* 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
@@ -9118,7 +9331,7 @@
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case 150 /* TypeParameter */:
return node === parent.constraint;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return node === parent.constraint;
case 154 /* PropertyDeclaration */:
case 153 /* PropertySignature */:
@@ -9378,7 +9591,7 @@
}
ts.getContainingClass = getContainingClass;
function getThisContainer(node, includeArrowFunctions) {
- ts.Debug.assert(node.kind !== 279 /* SourceFile */);
+ ts.Debug.assert(node.kind !== 284 /* SourceFile */);
while (true) {
node = node.parent;
if (!node) {
@@ -9432,7 +9645,7 @@
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 243 /* EnumDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return node;
}
}
@@ -9515,6 +9728,11 @@
}
}
ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
+ function isSuperOrSuperProperty(node) {
+ return node.kind === 98 /* SuperKeyword */
+ || isSuperProperty(node);
+ }
+ ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
/**
* Determines whether a node is a property or element access expression for `super`.
*/
@@ -10140,7 +10358,7 @@
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
function isJSDocTypeAlias(node) {
- return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 309 /* JSDocTypedefTag */ || node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocTypeAlias = isJSDocTypeAlias;
function isTypeAlias(node) {
@@ -10284,7 +10502,7 @@
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 === 290 /* JSDocVariadicType */;
+ return node.dotDotDotToken !== undefined || !!type && type.kind === 295 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -10522,14 +10740,15 @@
}
ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
function getEffectiveBaseTypeNode(node) {
- if (isInJSFile(node)) {
+ var baseType = getClassExtendsHeritageElement(node);
+ if (baseType && isInJSFile(node)) {
// Prefer an @augments tag because it may have type parameters.
var tag = ts.getJSDocAugmentsTag(node);
if (tag) {
return tag.class;
}
}
- return getClassExtendsHeritageElement(node);
+ return baseType;
}
ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
function getClassExtendsHeritageElement(node) {
@@ -10768,7 +10987,7 @@
|| kind === 158 /* GetAccessor */
|| kind === 159 /* SetAccessor */
|| kind === 244 /* ModuleDeclaration */
- || kind === 279 /* SourceFile */;
+ || kind === 284 /* SourceFile */;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(range) {
@@ -10845,7 +11064,7 @@
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return 0;
case 208 /* SpreadElement */:
return 1;
@@ -11163,6 +11382,9 @@
lineStart = true;
}
}
+ function getTextPosWithWriteLine() {
+ return lineStart ? output.length : (output.length + newLine.length);
+ }
reset();
return {
write: write,
@@ -11191,7 +11413,8 @@
writeStringLiteral: write,
writeSymbol: function (s, _) { return write(s); },
writeTrailingSemicolon: write,
- writeComment: write
+ writeComment: write,
+ getTextPosWithWriteLine: getTextPosWithWriteLine
};
}
ts.createTextWriter = createTextWriter;
@@ -11320,23 +11543,27 @@
function getSourceFilesToEmit(host, targetSourceFile) {
var options = host.getCompilerOptions();
var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); };
+ var getResolvedProjectReferenceToRedirect = function (fileName) { return host.getResolvedProjectReferenceToRedirect(fileName); };
if (options.outFile || options.out) {
var moduleKind = ts.getEmitModuleKind(options);
var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
// Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
return ts.filter(host.getSourceFiles(), function (sourceFile) {
- return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary);
+ return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect);
});
}
else {
var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
- return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); });
+ return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
}
}
ts.getSourceFilesToEmit = getSourceFilesToEmit;
/** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
- function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) {
- return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile);
+ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect) {
+ return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
+ !sourceFile.isDeclarationFile &&
+ !isSourceFileFromExternalLibrary(sourceFile) &&
+ !(isJsonSourceFile(sourceFile) && getResolvedProjectReferenceToRedirect(sourceFile.fileName));
}
ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
function getSourceFilePathInNewDir(fileName, host, newDirPath) {
@@ -11482,7 +11709,7 @@
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 === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 296 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
}
/**
* Gets the effective type annotation of the value parameter of a set accessor. If the node
@@ -12387,7 +12614,7 @@
}
ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
function getObjectFlags(type) {
- return type.flags & 524288 /* Object */ ? type.objectFlags : 0;
+ return type.flags & 3899392 /* ObjectFlagsType */ ? type.objectFlags : 0;
}
ts.getObjectFlags = getObjectFlags;
function typeHasCallOrConstructSignatures(type, checker) {
@@ -12454,25 +12681,37 @@
|| kind === 96 /* NullKeyword */
|| kind === 132 /* NeverKeyword */
|| kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
+ || kind === 289 /* JSDocAllType */
+ || kind === 290 /* JSDocUnknownType */
+ || kind === 291 /* JSDocNullableType */
+ || kind === 292 /* JSDocNonNullableType */
+ || kind === 293 /* JSDocOptionalType */
+ || kind === 294 /* JSDocFunctionType */
+ || kind === 295 /* JSDocVariadicType */;
}
ts.isTypeNodeKind = isTypeNodeKind;
function isAccessExpression(node) {
return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */;
}
ts.isAccessExpression = isAccessExpression;
+ function isBundleFileTextLike(section) {
+ switch (section.kind) {
+ case "text" /* Text */:
+ case "internal" /* Internal */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isBundleFileTextLike = isBundleFileTextLike;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
switch (options.target) {
- case 6 /* ESNext */:
+ case 7 /* ESNext */:
return "lib.esnext.full.d.ts";
+ case 6 /* ES2019 */:
+ return "lib.es2019.full.d.ts";
case 5 /* ES2018 */:
return "lib.es2018.full.d.ts";
case 4 /* ES2017 */:
@@ -12926,8 +13165,8 @@
switch (declaration.kind) {
case 72 /* Identifier */:
return declaration;
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */: {
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */: {
var name = declaration.name;
if (name.kind === 148 /* QualifiedName */) {
return name.right;
@@ -12951,7 +13190,7 @@
return undefined;
}
}
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
case 254 /* ExportAssignment */: {
var expression = declaration.expression;
@@ -13155,7 +13394,7 @@
return ts.emptyArray;
}
if (ts.isJSDocTypeAlias(node)) {
- ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */);
+ ts.Debug.assert(node.parent.kind === 296 /* JSDocComment */);
return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
}
if (node.typeParameters) {
@@ -13417,12 +13656,17 @@
return node.kind === 194 /* TypeAssertionExpression */;
}
ts.isTypeAssertion = isTypeAssertion;
+ function isConstTypeReference(node) {
+ return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
+ node.typeName.escapedText === "const" && !node.typeArguments;
+ }
+ ts.isConstTypeReference = isConstTypeReference;
function isParenthesizedExpression(node) {
return node.kind === 195 /* ParenthesizedExpression */;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 308 /* PartiallyEmittedExpression */) {
+ while (node.kind === 313 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13769,108 +14013,128 @@
ts.isEnumMember = isEnumMember;
// Top-level nodes
function isSourceFile(node) {
- return node.kind === 279 /* SourceFile */;
+ return node.kind === 284 /* SourceFile */;
}
ts.isSourceFile = isSourceFile;
function isBundle(node) {
- return node.kind === 280 /* Bundle */;
+ return node.kind === 285 /* Bundle */;
}
ts.isBundle = isBundle;
function isUnparsedSource(node) {
- return node.kind === 281 /* UnparsedSource */;
+ return node.kind === 286 /* UnparsedSource */;
}
ts.isUnparsedSource = isUnparsedSource;
+ function isUnparsedPrepend(node) {
+ return node.kind === 280 /* UnparsedPrepend */;
+ }
+ ts.isUnparsedPrepend = isUnparsedPrepend;
+ function isUnparsedTextLike(node) {
+ switch (node.kind) {
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isUnparsedTextLike = isUnparsedTextLike;
+ function isUnparsedNode(node) {
+ return isUnparsedTextLike(node) ||
+ node.kind === 279 /* UnparsedPrologue */ ||
+ node.kind === 283 /* UnparsedSyntheticReference */;
+ }
+ ts.isUnparsedNode = isUnparsedNode;
// JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 283 /* JSDocTypeExpression */;
+ return node.kind === 288 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 284 /* JSDocAllType */;
+ return node.kind === 289 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 285 /* JSDocUnknownType */;
+ return node.kind === 290 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 286 /* JSDocNullableType */;
+ return node.kind === 291 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 287 /* JSDocNonNullableType */;
+ return node.kind === 292 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 288 /* JSDocOptionalType */;
+ return node.kind === 293 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 289 /* JSDocFunctionType */;
+ return node.kind === 294 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 290 /* JSDocVariadicType */;
+ return node.kind === 295 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 291 /* JSDocComment */;
+ return node.kind === 296 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 295 /* JSDocAugmentsTag */;
+ return node.kind === 300 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 296 /* JSDocClassTag */;
+ return node.kind === 301 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocEnumTag(node) {
- return node.kind === 298 /* JSDocEnumTag */;
+ return node.kind === 303 /* JSDocEnumTag */;
}
ts.isJSDocEnumTag = isJSDocEnumTag;
function isJSDocThisTag(node) {
- return node.kind === 301 /* JSDocThisTag */;
+ return node.kind === 306 /* JSDocThisTag */;
}
ts.isJSDocThisTag = isJSDocThisTag;
function isJSDocParameterTag(node) {
- return node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 300 /* JSDocReturnTag */;
+ return node.kind === 305 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 302 /* JSDocTypeTag */;
+ return node.kind === 307 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 303 /* JSDocTemplateTag */;
+ return node.kind === 308 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 304 /* JSDocTypedefTag */;
+ return node.kind === 309 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */;
+ return node.kind === 310 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 310 /* JSDocPropertyTag */ || node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 292 /* JSDocTypeLiteral */;
+ return node.kind === 297 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
function isJSDocCallbackTag(node) {
- return node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocCallbackTag = isJSDocCallbackTag;
function isJSDocSignature(node) {
- return node.kind === 293 /* JSDocSignature */;
+ return node.kind === 298 /* JSDocSignature */;
}
ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
@@ -13881,7 +14145,7 @@
(function (ts) {
/* @internal */
function isSyntaxList(n) {
- return n.kind === 306 /* SyntaxList */;
+ return n.kind === 311 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
/* @internal */
@@ -14033,11 +14297,11 @@
switch (kind) {
case 155 /* MethodSignature */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 166 /* ConstructorType */:
return true;
default:
@@ -14328,8 +14592,8 @@
case 208 /* SpreadElement */:
case 212 /* AsExpression */:
case 210 /* OmittedExpression */:
- case 309 /* CommaListExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 314 /* CommaListExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -14343,12 +14607,12 @@
ts.isAssertionExpression = isAssertionExpression;
/* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 308 /* PartiallyEmittedExpression */;
+ return node.kind === 313 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
/* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 307 /* NotEmittedStatement */;
+ return node.kind === 312 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
@@ -14459,9 +14723,9 @@
|| kind === 242 /* TypeAliasDeclaration */
|| kind === 150 /* TypeParameter */
|| kind === 237 /* VariableDeclaration */
- || kind === 304 /* JSDocTypedefTag */
- || kind === 297 /* JSDocCallbackTag */
- || kind === 305 /* JSDocPropertyTag */;
+ || kind === 309 /* JSDocTypedefTag */
+ || kind === 302 /* JSDocCallbackTag */
+ || kind === 310 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
return kind === 239 /* FunctionDeclaration */
@@ -14496,14 +14760,14 @@
|| kind === 219 /* VariableStatement */
|| kind === 224 /* WhileStatement */
|| kind === 231 /* WithStatement */
- || kind === 307 /* NotEmittedStatement */
- || kind === 311 /* EndOfDeclarationMarker */
- || kind === 310 /* MergeDeclarationMarker */;
+ || kind === 312 /* NotEmittedStatement */
+ || kind === 316 /* EndOfDeclarationMarker */
+ || kind === 315 /* MergeDeclarationMarker */;
}
/* @internal */
function isDeclaration(node) {
if (node.kind === 150 /* TypeParameter */) {
- return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node);
+ return (node.parent && node.parent.kind !== 308 /* JSDocTemplateTag */) || ts.isInJSFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -14598,18 +14862,18 @@
/** True if node is of some JSDoc syntax kind. */
/* @internal */
function isJSDocNode(node) {
- return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */;
+ return node.kind >= 288 /* FirstJSDocNode */ && node.kind <= 310 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
+ return node.kind === 296 /* 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 >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */;
+ return node.kind >= 299 /* FirstJSDocTagNode */ && node.kind <= 310 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -14926,6 +15190,10 @@
return !!(compilerOptions.declaration || compilerOptions.composite);
}
ts.getEmitDeclarations = getEmitDeclarations;
+ function isIncrementalCompilation(options) {
+ return !!(options.incremental || options.composite);
+ }
+ ts.isIncrementalCompilation = isIncrementalCompilation;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
}
@@ -15613,7 +15881,7 @@
}
ts.getRegexFromPattern = getRegexFromPattern;
/** @param path directory of the tsconfig.json */
- function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) {
+ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
path = ts.normalizePath(path);
currentDirectory = ts.normalizePath(currentDirectory);
var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
@@ -15623,12 +15891,18 @@
// Associate an array of results with each include regex. This keeps results in order of the "include" order.
// If there are no "includes", then just put everything in results[0].
var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
+ var visited = ts.createMap();
+ var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
var basePath = _a[_i];
visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
}
return ts.flatten(results);
function visitDirectory(path, absolutePath, depth) {
+ var canonicalPath = toCanonical(realpath(absolutePath));
+ if (visited.has(canonicalPath))
+ return;
+ visited.set(canonicalPath, true);
var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
var _loop_1 = function (current) {
var name = combinePaths(path, current);
@@ -16011,6 +16285,19 @@
return arr.slice(index);
}
ts.sliceAfter = sliceAfter;
+ function addRelatedInfo(diagnostic) {
+ var _a;
+ var relatedInformation = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ relatedInformation[_i - 1] = arguments[_i];
+ }
+ if (!diagnostic.relatedInformation) {
+ diagnostic.relatedInformation = [];
+ }
+ (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
+ return diagnostic;
+ }
+ ts.addRelatedInfo = addRelatedInfo;
function minAndMax(arr, getValue) {
Debug.assert(arr.length !== 0);
var min = getValue(arr[0]);
@@ -16210,7 +16497,7 @@
var SourceFileConstructor;
// tslint:enable variable-name
function createNode(kind, pos, end) {
- if (kind === 279 /* SourceFile */) {
+ if (kind === 284 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 72 /* Identifier */) {
@@ -16461,7 +16748,7 @@
case 218 /* Block */:
case 245 /* ModuleBlock */:
return visitNodes(cbNode, cbNodes, node.statements);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return visitNodes(cbNode, cbNodes, node.statements) ||
visitNode(cbNode, node.endOfFileToken);
case 219 /* VariableStatement */:
@@ -16610,7 +16897,7 @@
return visitNode(cbNode, node.expression);
case 258 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
case 260 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
@@ -16639,60 +16926,60 @@
return visitNode(cbNode, node.tagName);
case 171 /* OptionalType */:
case 172 /* RestType */:
- case 283 /* JSDocTypeExpression */:
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 288 /* JSDocOptionalType */:
- case 290 /* JSDocVariadicType */:
+ case 288 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 293 /* JSDocOptionalType */:
+ case 295 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return visitNode(cbNode, node.tagName) ||
(node.isNameFirst
? visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression)
: visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name));
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.constraint) ||
visitNodes(cbNode, cbNodes, node.typeParameters);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return visitNode(cbNode, node.tagName) ||
(node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ node.typeExpression.kind === 288 /* JSDocTypeExpression */
? visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName)
: visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression));
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.typeExpression);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return ts.forEach(node.jsDocPropertyTags, cbNode);
- case 294 /* JSDocTag */:
- case 296 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
return visitNode(cbNode, node.tagName);
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -16772,7 +17059,7 @@
(function (Parser) {
// Share a single scanner across all calls to parse a source file. This helps speed things
// up by avoiding the cost of creating/compiling scanners over and over again.
- var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true);
+ var scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ true);
var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */;
// capture constructors in 'initializeState' to avoid null checks
// tslint:disable variable-name
@@ -17066,7 +17353,7 @@
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(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
+ var sourceFile = new SourceFileConstructor(284 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
@@ -18266,9 +18553,9 @@
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(284 /* JSDocAllType */);
+ var result = createNode(289 /* JSDocAllType */);
if (postFixEquals) {
- return createPostfixType(288 /* JSDocOptionalType */, result);
+ return createPostfixType(293 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -18276,7 +18563,7 @@
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(287 /* JSDocNonNullableType */);
+ var result = createNode(292 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -18300,18 +18587,18 @@
token() === 30 /* GreaterThanToken */ ||
token() === 59 /* EqualsToken */ ||
token() === 50 /* BarToken */) {
- var result = createNode(285 /* JSDocUnknownType */, pos);
+ var result = createNode(290 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(286 /* JSDocNullableType */, pos);
+ var result = createNode(291 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(289 /* JSDocFunctionType */);
+ var result = createNodeWithJSDoc(294 /* JSDocFunctionType */);
nextToken();
fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
@@ -18335,12 +18622,12 @@
var type = parseTypeOrTypePredicate();
scanner.setInJSDocType(false);
if (dotdotdot) {
- var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos);
+ var variadic = createNode(295 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 59 /* EqualsToken */) {
- return createPostfixType(288 /* JSDocOptionalType */, type);
+ return createPostfixType(293 /* JSDocOptionalType */, type);
}
return type;
}
@@ -18712,7 +18999,7 @@
return finishNode(node);
}
var type = parseType();
- if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) {
+ if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 291 /* JSDocNullableType */ && type.pos === type.type.pos) {
type.kind = 171 /* OptionalType */;
}
return type;
@@ -18850,6 +19137,7 @@
case 135 /* NumberKeyword */:
case 146 /* BigIntKeyword */:
case 123 /* BooleanKeyword */:
+ case 133 /* ReadonlyKeyword */:
case 139 /* SymbolKeyword */:
case 142 /* UniqueKeyword */:
case 106 /* VoidKeyword */:
@@ -18898,14 +19186,14 @@
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 52 /* ExclamationToken */:
- type = createPostfixType(287 /* JSDocNonNullableType */, type);
+ type = createPostfixType(292 /* JSDocNonNullableType */, type);
break;
case 56 /* 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 = createPostfixType(286 /* JSDocNullableType */, type);
+ type = createPostfixType(291 /* JSDocNullableType */, type);
break;
case 22 /* OpenBracketToken */:
parseExpected(22 /* OpenBracketToken */);
@@ -18955,6 +19243,7 @@
switch (operator) {
case 129 /* KeyOfKeyword */:
case 142 /* UniqueKeyword */:
+ case 133 /* ReadonlyKeyword */:
return parseTypeOperator(operator);
case 127 /* InferKeyword */:
return parseInferType();
@@ -20014,7 +20303,8 @@
}
function parseJsxText() {
var node = createNode(11 /* JsxText */);
- node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
+ node.text = scanner.getTokenValue();
+ node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
currentToken = scanner.scanJsxToken();
return finishNode(node);
}
@@ -21829,8 +22119,8 @@
var JSDocParser;
(function (JSDocParser) {
function parseJSDocTypeExpressionForTests(content, start, length) {
- initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
- sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
+ initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ sourceFile = createSourceFile("file.js", 7 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
scanner.setText(content, start, length);
currentToken = scanner.scan();
var jsDocTypeExpression = parseJSDocTypeExpression();
@@ -21841,7 +22131,7 @@
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
// Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(283 /* JSDocTypeExpression */);
+ var result = createNode(288 /* JSDocTypeExpression */);
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -21852,7 +22142,7 @@
}
JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
function parseIsolatedJSDocComment(content, start, length) {
- initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion
var jsDoc = parseJSDocCommentWorker(start, length);
var diagnostics = parseDiagnostics;
@@ -22004,7 +22294,7 @@
}
}
function createJSDocComment() {
- var result = createNode(291 /* JSDocComment */, start);
+ var result = createNode(296 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -22171,7 +22461,7 @@
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(start, tagName) {
- var result = createNode(294 /* JSDocTag */, start);
+ var result = createNode(299 /* JSDocTag */, start);
result.tagName = tagName;
return finishNode(result);
}
@@ -22230,8 +22520,8 @@
typeExpression = tryParseTypeExpression();
}
var result = target === 1 /* Property */ ?
- createNode(305 /* JSDocPropertyTag */, start) :
- createNode(299 /* JSDocParameterTag */, start);
+ createNode(310 /* JSDocPropertyTag */, start) :
+ createNode(304 /* JSDocParameterTag */, start);
var comment = parseTagComments(indent + scanner.getStartPos() - start);
var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
if (nestedTypeLiteral) {
@@ -22248,18 +22538,18 @@
}
function parseNestedTypeLiteral(typeExpression, name, target, indent) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(288 /* 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, indent, name); })) {
- if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) {
+ if (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 169 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
@@ -22270,25 +22560,25 @@
}
}
function parseReturnTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 305 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(300 /* JSDocReturnTag */, start);
+ var result = createNode(305 /* JSDocReturnTag */, start);
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 307 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(302 /* JSDocTypeTag */, start);
+ var result = createNode(307 /* JSDocTypeTag */, start);
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(start, tagName) {
- var result = createNode(295 /* JSDocAugmentsTag */, start);
+ var result = createNode(300 /* JSDocAugmentsTag */, start);
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
return finishNode(result);
@@ -22315,19 +22605,19 @@
return node;
}
function parseClassTag(start, tagName) {
- var tag = createNode(296 /* JSDocClassTag */, start);
+ var tag = createNode(301 /* JSDocClassTag */, start);
tag.tagName = tagName;
return finishNode(tag);
}
function parseThisTag(start, tagName) {
- var tag = createNode(301 /* JSDocThisTag */, start);
+ var tag = createNode(306 /* JSDocThisTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
return finishNode(tag);
}
function parseEnumTag(start, tagName) {
- var tag = createNode(298 /* JSDocEnumTag */, start);
+ var tag = createNode(303 /* JSDocEnumTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
@@ -22336,7 +22626,7 @@
function parseTypedefTag(start, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespaceOrAsterisk();
- var typedefTag = createNode(304 /* JSDocTypedefTag */, start);
+ var typedefTag = createNode(309 /* JSDocTypedefTag */, start);
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace();
typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
@@ -22350,9 +22640,9 @@
var childTypeTag = void 0;
while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start);
}
- if (child.kind === 302 /* JSDocTypeTag */) {
+ if (child.kind === 307 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -22398,14 +22688,14 @@
return typeNameOrNamespaceName;
}
function parseCallbackTag(start, tagName, indent) {
- var callbackTag = createNode(297 /* JSDocCallbackTag */, start);
+ var callbackTag = createNode(302 /* JSDocCallbackTag */, start);
callbackTag.tagName = tagName;
callbackTag.fullName = parseJSDocTypeNameWithNamespace();
callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
skipWhitespace();
callbackTag.comment = parseTagComments(indent);
var child;
- var jsdocSignature = createNode(293 /* JSDocSignature */, start);
+ var jsdocSignature = createNode(298 /* JSDocSignature */, start);
jsdocSignature.parameters = [];
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
@@ -22413,7 +22703,7 @@
var returnTag = tryParse(function () {
if (parseOptionalJsdoc(58 /* AtToken */)) {
var tag = parseTag(indent);
- if (tag && tag.kind === 300 /* JSDocReturnTag */) {
+ if (tag && tag.kind === 305 /* JSDocReturnTag */) {
return tag;
}
}
@@ -22458,7 +22748,7 @@
case 58 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target, indent);
- if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) &&
+ if (child && (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) &&
target !== 4 /* CallbackParameter */ &&
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
@@ -22528,7 +22818,7 @@
skipWhitespace();
typeParameters.push(typeParameter);
} while (parseOptionalJsdoc(27 /* CommaToken */));
- var result = createNode(303 /* JSDocTemplateTag */, start);
+ var result = createNode(308 /* JSDocTemplateTag */, start);
result.tagName = tagName;
result.constraint = constraint;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -23306,6 +23596,7 @@
["es2016", "lib.es2016.d.ts"],
["es2017", "lib.es2017.d.ts"],
["es2018", "lib.es2018.d.ts"],
+ ["es2019", "lib.es2019.d.ts"],
["esnext", "lib.esnext.d.ts"],
// Host only
["dom", "lib.dom.d.ts"],
@@ -23329,12 +23620,16 @@
["es2017.string", "lib.es2017.string.d.ts"],
["es2017.intl", "lib.es2017.intl.d.ts"],
["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
+ ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
["es2018.intl", "lib.es2018.intl.d.ts"],
["es2018.promise", "lib.es2018.promise.d.ts"],
["es2018.regexp", "lib.es2018.regexp.d.ts"],
- ["esnext.array", "lib.esnext.array.d.ts"],
- ["esnext.symbol", "lib.esnext.symbol.d.ts"],
- ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"],
+ ["es2019.array", "lib.es2019.array.d.ts"],
+ ["es2019.string", "lib.es2019.string.d.ts"],
+ ["es2019.symbol", "lib.es2019.symbol.d.ts"],
+ ["esnext.array", "lib.es2019.array.d.ts"],
+ ["esnext.symbol", "lib.es2019.symbol.d.ts"],
+ ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
["esnext.intl", "lib.esnext.intl.d.ts"],
["esnext.bigint", "lib.esnext.bigint.d.ts"]
];
@@ -23480,14 +23775,15 @@
es2016: 3 /* ES2016 */,
es2017: 4 /* ES2017 */,
es2018: 5 /* ES2018 */,
- esnext: 6 /* ESNext */,
+ es2019: 6 /* ES2019 */,
+ esnext: 7 /* ESNext */,
}),
affectsSourceFile: true,
affectsModuleResolution: true,
paramType: ts.Diagnostics.VERSION,
showInSimplifiedHelpView: true,
category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT,
+ description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT,
},
{
name: "module",
@@ -23609,6 +23905,22 @@
description: ts.Diagnostics.Enable_project_compilation,
},
{
+ name: "incremental",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_incremental_compilation,
+ },
+ {
+ name: "tsBuildInfoFile",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE,
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
+ },
+ {
name: "removeComments",
type: "boolean",
showInSimplifiedHelpView: true,
@@ -25034,7 +25346,7 @@
}
function directoryOfCombinedPath(fileName, basePath) {
// Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
- // until consistient casing errors are reported
+ // until consistent casing errors are reported
return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
}
/**
@@ -27326,7 +27638,7 @@
return "__constructor" /* Constructor */;
case 165 /* FunctionType */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return "__call" /* Call */;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
@@ -27335,7 +27647,7 @@
return "__index" /* Index */;
case 255 /* ExportDeclaration */:
return "__export" /* ExportStar */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// json file should behave as
// module.exports = ...
return "export=" /* ExportEquals */;
@@ -27346,12 +27658,12 @@
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
case 151 /* 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 === 289 /* 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 === 294 /* 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;
@@ -27435,13 +27747,15 @@
message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
messageNeedsName_1 = false;
}
- if (symbol.declarations && symbol.declarations.length) {
+ var multipleDefaultExports_1 = false;
+ if (ts.length(symbol.declarations)) {
// If the current node is a default export of some sort, then check if
// there are any other default exports that we need to error on.
// 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;
+ multipleDefaultExports_1 = true;
}
else {
// This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
@@ -27452,14 +27766,22 @@
(node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) {
message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
messageNeedsName_1 = false;
+ multipleDefaultExports_1 = true;
}
}
}
- 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);
+ var declarationName_1 = ts.getNameOfDeclaration(node) || node;
+ var relatedInformation_1 = [];
+ ts.forEach(symbol.declarations, function (declaration, index) {
+ var decl = ts.getNameOfDeclaration(declaration) || declaration;
+ var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
+ file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo(diag, createDiagnosticForNode(declarationName_1, index === 0 ? ts.Diagnostics.Another_export_default_is_here : ts.Diagnostics.and_here)) : diag);
+ if (multipleDefaultExports_1) {
+ relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
+ }
+ });
+ var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
+ file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInformation_1)) : diag);
symbol = createSymbol(0 /* None */, name);
}
}
@@ -27575,7 +27897,7 @@
}
}
// We create a return control flow graph for IIFEs and constructors. For constructors
- // we use the return control flow graph in strict property intialization checks.
+ // we use the return control flow graph in strict property initialization checks.
currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined;
currentBreakTarget = undefined;
currentContinueTarget = undefined;
@@ -27590,7 +27912,7 @@
if (hasExplicitReturn)
node.flags |= 256 /* HasExplicitReturn */;
}
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
node.flags |= emitFlags;
}
if (currentReturnTarget) {
@@ -27734,12 +28056,12 @@
case 191 /* CallExpression */:
bindCallExpressionFlow(node);
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
bindJSDocTypeAlias(node);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
- case 279 /* SourceFile */: {
+ case 284 /* SourceFile */: {
bindEachFunctionsFirst(node.statements);
bind(node.endOfFileToken);
break;
@@ -28426,7 +28748,7 @@
case 243 /* EnumDeclaration */:
case 188 /* ObjectLiteralExpression */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 268 /* JsxAttributes */:
return 1 /* IsContainer */;
case 241 /* InterfaceDeclaration */:
@@ -28435,7 +28757,7 @@
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
return 1 /* IsContainer */ | 32 /* HasLocals */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
case 156 /* MethodDeclaration */:
if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
@@ -28448,8 +28770,8 @@
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
- case 289 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
case 165 /* FunctionType */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
@@ -28503,7 +28825,7 @@
// handlers to take care of declaring these child members.
case 244 /* ModuleDeclaration */:
return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return declareSourceFileMember(node, symbolFlags, symbolExcludes);
case 209 /* ClassExpression */:
case 240 /* ClassDeclaration */:
@@ -28511,7 +28833,7 @@
case 243 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 188 /* ObjectLiteralExpression */:
case 241 /* InterfaceDeclaration */:
case 268 /* JsxAttributes */:
@@ -28525,7 +28847,7 @@
case 166 /* ConstructorType */:
case 160 /* CallSignature */:
case 161 /* ConstructSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 162 /* IndexSignature */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
@@ -28535,9 +28857,9 @@
case 239 /* FunctionDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
- case 289 /* JSDocFunctionType */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 294 /* JSDocFunctionType */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
// All the children of these container types are never visible through another
@@ -28560,8 +28882,8 @@
: declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node) {
- var body = node.kind === 279 /* SourceFile */ ? node : node.body;
- if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
+ var body = node.kind === 284 /* SourceFile */ ? node : node.body;
+ if (body && (body.kind === 284 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
var stat = _a[_i];
if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) {
@@ -28695,7 +29017,7 @@
case 244 /* ModuleDeclaration */:
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalOrCommonJsModule(container)) {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
@@ -28833,7 +29155,7 @@
function checkStrictModeFunctionDeclaration(node) {
if (languageVersion < 2 /* ES2015 */) {
// Report error if function is not top level function declaration
- if (blockScopeContainer.kind !== 279 /* SourceFile */ &&
+ if (blockScopeContainer.kind !== 284 /* SourceFile */ &&
blockScopeContainer.kind !== 244 /* ModuleDeclaration */ &&
!ts.isFunctionLike(blockScopeContainer)) {
// We check first if the name is inside class declaration or class expression; if so give explicit message
@@ -29108,12 +29430,12 @@
case 159 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */);
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
case 166 /* ConstructorType */:
return bindFunctionOrConstructorType(node);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 181 /* MappedType */:
return bindAnonymousTypeWorker(node);
case 188 /* ObjectLiteralExpression */:
@@ -29172,7 +29494,7 @@
return bindExportDeclaration(node);
case 254 /* ExportAssignment */:
return bindExportAssignment(node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
updateStrictModeStatementList(node.statements);
return bindSourceFileIfExternalModule();
case 218 /* Block */:
@@ -29182,22 +29504,22 @@
// falls through
case 245 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
- case 299 /* JSDocParameterTag */:
- if (node.parent.kind === 293 /* JSDocSignature */) {
+ case 304 /* JSDocParameterTag */:
+ if (node.parent.kind === 298 /* JSDocSignature */) {
return bindParameter(node);
}
- if (node.parent.kind !== 292 /* JSDocTypeLiteral */) {
+ if (node.parent.kind !== 297 /* JSDocTypeLiteral */) {
break;
}
// falls through
- case 305 /* JSDocPropertyTag */:
+ case 310 /* JSDocPropertyTag */:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 293 /* JSDocOptionalType */ ?
4 /* Property */ | 16777216 /* Optional */ :
4 /* Property */;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
}
}
@@ -29369,9 +29691,14 @@
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 279 /* SourceFile */:
- // this.foo assignment in a source file
- // Do not bind. It would be nice to support this someday though.
+ case 284 /* SourceFile */:
+ // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
+ if (thisContainer.commonJsModuleIndicator) {
+ declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220414 /* FunctionScopedVariableExcludes */);
+ }
break;
default:
ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer));
@@ -29381,7 +29708,7 @@
if (node.expression.kind === 100 /* ThisKeyword */) {
bindThisPropertyAssignment(node);
}
- else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) {
+ else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 284 /* SourceFile */) {
if (ts.isPrototypeAccess(node.expression)) {
bindPrototypePropertyAssignment(node, node.parent);
}
@@ -29418,7 +29745,7 @@
}
function bindObjectDefinePropertyAssignment(node) {
var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
- var isToplevel = node.parent.parent.kind === 279 /* SourceFile */;
+ var isToplevel = node.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false);
bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
}
@@ -29485,8 +29812,8 @@
function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
var namespaceSymbol = lookupSymbolForPropertyAccess(name);
var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
- ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */
- : propertyAccess.parent.parent.kind === 279 /* SourceFile */;
+ ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 284 /* SourceFile */
+ : propertyAccess.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty);
bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
}
@@ -29624,7 +29951,7 @@
}
}
function bindParameter(node) {
- if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) {
+ if (node.kind === 304 /* JSDocParameterTag */ && container.kind !== 298 /* JSDocSignature */) {
return;
}
if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) {
@@ -29882,44 +30209,37 @@
ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
function computeCallExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
+ var callee = ts.skipOuterExpressions(node.expression);
var expression = node.expression;
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */
- || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) {
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) {
// If the this node contains a SpreadExpression, or is a super call, then it is an ES6
// node.
- transformFlags |= 192 /* AssertES2015 */;
- // super property or element accesses could be inside lambdas, etc, and need a captured `this`,
- // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor)
- if (expression.transformFlags & 67108864 /* ContainsSuper */) {
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 128 /* AssertES2015 */;
+ if (ts.isSuperProperty(callee)) {
+ transformFlags |= 2048 /* ContainsLexicalThis */;
}
}
if (expression.kind === 92 /* ImportKeyword */) {
- transformFlags |= 16777216 /* ContainsDynamicImport */;
- // A dynamic 'import()' call that contains a lexical 'this' will
- // require a captured 'this' when emitting down-level.
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- transformFlags |= 16384 /* ContainsCapturedLexicalThis */;
- }
+ transformFlags |= 524288 /* ContainsDynamicImport */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */;
}
function computeNewExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */) {
// If the this node contains a SpreadElementExpression then it is an ES6
// node.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */;
}
function computeBinaryExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -29927,20 +30247,20 @@
var leftKind = node.left.kind;
if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) {
// Destructuring object assignments with are ES2015 syntax
- // and possibly ESNext if they contain rest
- transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
+ // and possibly ES2018 if they contain rest
+ transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */;
}
else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) {
// Destructuring assignments are ES2015 syntax.
- transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
+ transformFlags |= 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */;
}
else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */
|| operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) {
// Exponentiation is ES2016 syntax.
- transformFlags |= 32 /* AssertES2016 */;
+ transformFlags |= 64 /* AssertES2016 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeParameter(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -29951,147 +30271,131 @@
// syntax.
if (node.questionToken
|| node.type
- || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
+ || (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
|| ts.isThisIdentifier(name)) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// If a parameter has an accessibility modifier, then it is TypeScript syntax.
if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
- transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */;
}
- // parameters with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // parameters with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a parameter has an initializer, a binding pattern or a dotDotDot token, then
// it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
- if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
- transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */;
+ if (subtreeFlags & 65536 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* ParameterExcludes */;
+ return transformFlags & ~536870912 /* ParameterExcludes */;
}
function computeParenthesizedExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
var expression = node.expression;
var expressionKind = expression.kind;
- var expressionTransformFlags = expression.transformFlags;
// 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 === 212 /* AsExpression */
|| expressionKind === 194 /* TypeAssertionExpression */) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- // If the expression of a ParenthesizedExpression is a destructuring assignment,
- // then the ParenthesizedExpression is a destructuring assignment.
- if (expressionTransformFlags & 1024 /* DestructuringAssignment */) {
- transformFlags |= 1024 /* DestructuringAssignment */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536872257 /* OuterExpressionExcludes */;
+ return transformFlags & ~536870912 /* OuterExpressionExcludes */;
}
function computeClassDeclaration(node, subtreeFlags) {
var transformFlags;
if (ts.hasModifier(node, 2 /* Ambient */)) {
// An ambient declaration is TypeScript syntax.
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
// A ClassDeclaration is ES6 syntax.
- transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// A class with a parameter property assignment, property initializer, computed property name, or decorator is
// TypeScript syntax.
// An exported declaration may be TypeScript syntax, but is handled by the visitor
// for a namespace declaration.
- if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */)
+ if ((subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */)
|| node.typeParameters) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~638121281 /* ClassExcludes */;
+ return transformFlags & ~536888320 /* ClassExcludes */;
}
function computeClassExpression(node, subtreeFlags) {
// A ClassExpression is ES6 syntax.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// A class with a parameter property assignment, property initializer, or decorator is
// TypeScript syntax.
- if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */
+ if (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */
|| node.typeParameters) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~638121281 /* ClassExcludes */;
+ return transformFlags & ~536888320 /* ClassExcludes */;
}
function computeHeritageClause(node, subtreeFlags) {
var transformFlags = subtreeFlags;
switch (node.token) {
case 86 /* ExtendsKeyword */:
// An `extends` HeritageClause is ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 109 /* ImplementsKeyword */:
// An `implements` HeritageClause is TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
break;
default:
ts.Debug.fail("Unexpected token for heritage clause");
break;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeCatchClause(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (!node.variableDeclaration) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 8 /* AssertES2019 */;
}
else if (ts.isBindingPattern(node.variableDeclaration.name)) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637797697 /* CatchClauseExcludes */;
+ return transformFlags & ~536879104 /* CatchClauseExcludes */;
}
function computeExpressionWithTypeArguments(node, subtreeFlags) {
// An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
// extends clause of a class.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// If an ExpressionWithTypeArguments contains type arguments, then it
// is TypeScript syntax.
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeConstructor(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// TypeScript-specific modifiers and overloads are TypeScript syntax
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* ConstructorExcludes */;
+ return transformFlags & ~537372672 /* ConstructorExcludes */;
}
function computeMethod(node, subtreeFlags) {
// A MethodDeclaration is ES6 syntax.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
// overloads are TypeScript syntax.
if (node.decorators
@@ -30100,21 +30404,21 @@
|| node.type
|| (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// An async method declaration is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* MethodOrAccessorExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */);
}
function computeAccessor(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -30125,25 +30429,25 @@
|| node.type
|| (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* MethodOrAccessorExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */);
}
function computePropertyDeclaration(node, subtreeFlags) {
// A PropertyDeclaration is TypeScript syntax.
- var transformFlags = subtreeFlags | 3 /* AssertTypeScript */;
+ var transformFlags = subtreeFlags | 1 /* AssertTypeScript */;
// If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor
// so that it handle the transformation.
if (node.initializer || ts.isComputedPropertyName(node.name)) {
- transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1024 /* ContainsTypeScriptClassSyntax */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~536872960 /* PropertyExcludes */);
}
function computeFunctionDeclaration(node, subtreeFlags) {
var transformFlags;
@@ -30152,42 +30456,36 @@
if (!body || (modifierFlags & 2 /* Ambient */)) {
// An ambient declaration is TypeScript syntax.
// A FunctionDeclaration without a body is an overload and is TypeScript syntax.
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
- transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */;
+ transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */;
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (modifierFlags & 2270 /* TypeScriptModifier */
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async function declaration is ES2017 syntax.
if (modifierFlags & 256 /* Async */) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If a FunctionDeclaration's subtree has marked the container as needing to capture the
- // lexical this, or the function contains parameters with initializers, then this node is
- // ES6 syntax.
- if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) {
- transformFlags |= 192 /* AssertES2015 */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a FunctionDeclaration is generator function and is the body of a
// transformed async function, then this node can be transformed to a
// down-level generator.
- // Currently we do not support transforming any other generator fucntions
+ // Currently we do not support transforming any other generator functions
// down level.
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653620545 /* FunctionExcludes */;
+ return transformFlags & ~537373696 /* FunctionExcludes */;
}
function computeFunctionExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -30196,181 +30494,161 @@
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async function expression is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
- // function expressions with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If a FunctionExpression's subtree has marked the container as needing to capture the
- // lexical this, or the function contains parameters with initializers, then this node is
- // ES6 syntax.
- if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) {
- transformFlags |= 192 /* AssertES2015 */;
+ // function expressions with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a FunctionExpression is generator function and is the body of a
// transformed async function, then this node can be transformed to a
// down-level generator.
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653620545 /* FunctionExcludes */;
+ return transformFlags & ~537373696 /* FunctionExcludes */;
}
function computeArrowFunction(node, subtreeFlags) {
// An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async arrow function is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= 16 /* AssertES2017 */;
+ transformFlags |= 32 /* AssertES2017 */;
}
- // arrow functions with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If an ArrowFunction contains a lexical this, its container must capture the lexical this.
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- transformFlags |= 16384 /* ContainsCapturedLexicalThis */;
+ // arrow functions with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653604161 /* ArrowFunctionExcludes */;
+ return transformFlags & ~537371648 /* ArrowFunctionExcludes */;
}
function computePropertyAccess(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// If a PropertyAccessExpression starts with a super keyword, then it is
// ES6 syntax, and requires a lexical `this` binding.
- if (transformFlags & 33554432 /* Super */) {
- transformFlags ^= 33554432 /* Super */;
+ if (node.expression.kind === 98 /* SuperKeyword */) {
// super inside of an async function requires hoisting the super access (ES2017).
- // same for super inside of an async generator, which is ESNext.
- transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */;
+ // same for super inside of an async generator, which is ES2018.
+ transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~570426689 /* PropertyAccessExcludes */;
+ return transformFlags & ~536870912 /* PropertyAccessExcludes */;
}
function computeElementAccess(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- var expression = node.expression;
- var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing
// If an ElementAccessExpression starts with a super keyword, then it is
// ES6 syntax, and requires a lexical `this` binding.
- if (expressionFlags & 33554432 /* Super */) {
- transformFlags &= ~33554432 /* Super */;
+ if (node.expression.kind === 98 /* SuperKeyword */) {
// super inside of an async function requires hoisting the super access (ES2017).
- // same for super inside of an async generator, which is ESNext.
- transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */;
+ // same for super inside of an async generator, which is ES2018.
+ transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~570426689 /* PropertyAccessExcludes */;
+ return transformFlags & ~536870912 /* PropertyAccessExcludes */;
}
function computeVariableDeclaration(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- // A VariableDeclaration containing ObjectRest is ESNext syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally?
+ // A VariableDeclaration containing ObjectRest is ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// Type annotations are TypeScript syntax.
if (node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeVariableStatement(node, subtreeFlags) {
var transformFlags;
var declarationListTransformFlags = node.declarationList.transformFlags;
// An ambient declaration is TypeScript syntax.
if (ts.hasModifier(node, 2 /* Ambient */)) {
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
transformFlags = subtreeFlags;
- if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) {
- transformFlags |= 192 /* AssertES2015 */;
+ if (declarationListTransformFlags & 65536 /* ContainsBindingPattern */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeLabeledStatement(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
- if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */
+ if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */
&& ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeImportEquals(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// An ImportEqualsDeclaration with a namespace reference is TypeScript.
if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeExpressionStatement(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- // If the expression of an expression statement is a destructuring assignment,
- // then we treat the statement as ES6 so that we can indicate that we do not
- // need to hold on to the right-hand side.
- if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) {
- transformFlags |= 192 /* AssertES2015 */;
- }
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeModuleDeclaration(node, subtreeFlags) {
- var transformFlags = 3 /* AssertTypeScript */;
+ var transformFlags = 1 /* AssertTypeScript */;
var modifierFlags = ts.getModifierFlags(node);
if ((modifierFlags & 2 /* Ambient */) === 0) {
transformFlags |= subtreeFlags;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~647001409 /* ModuleExcludes */;
+ return transformFlags & ~537168896 /* ModuleExcludes */;
}
function computeVariableDeclarationList(node, subtreeFlags) {
- var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */;
- if (subtreeFlags & 2097152 /* ContainsBindingPattern */) {
- transformFlags |= 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */;
+ if (subtreeFlags & 65536 /* ContainsBindingPattern */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
// If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
if (node.flags & 3 /* BlockScoped */) {
- transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */;
+ transformFlags |= 128 /* AssertES2015 */ | 32768 /* ContainsBlockScopedBinding */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~639894849 /* VariableDeclarationListExcludes */;
+ return transformFlags & ~536944640 /* VariableDeclarationListExcludes */;
}
function computeOther(node, kind, subtreeFlags) {
// Mark transformations needed for each node
var transformFlags = subtreeFlags;
- var excludeFlags = 637535553 /* NodeExcludes */;
+ var excludeFlags = 536870912 /* NodeExcludes */;
switch (kind) {
case 121 /* AsyncKeyword */:
case 201 /* AwaitExpression */:
- // async/await is ES2017 syntax, but may be ESNext syntax (for async generators)
- transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */;
+ // async/await is ES2017 syntax, but may be ES2018 syntax (for async generators)
+ transformFlags |= 16 /* AssertES2018 */ | 32 /* AssertES2017 */;
break;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
// These nodes are TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
- excludeFlags = 536872257 /* OuterExpressionExcludes */;
+ transformFlags |= 1 /* AssertTypeScript */;
+ excludeFlags = 536870912 /* OuterExpressionExcludes */;
break;
case 115 /* PublicKeyword */:
case 113 /* PrivateKeyword */:
@@ -30383,7 +30661,7 @@
case 213 /* NonNullExpression */:
case 133 /* ReadonlyKeyword */:
// These nodes are TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
break;
case 260 /* JsxElement */:
case 261 /* JsxSelfClosingElement */:
@@ -30398,7 +30676,7 @@
case 269 /* JsxSpreadAttribute */:
case 270 /* JsxExpression */:
// These nodes are Jsx syntax.
- transformFlags |= 4 /* AssertJsx */;
+ transformFlags |= 2 /* AssertJsx */;
break;
case 14 /* NoSubstitutionTemplateLiteral */:
case 15 /* TemplateHead */:
@@ -30410,32 +30688,32 @@
case 116 /* StaticKeyword */:
case 214 /* MetaProperty */:
// These nodes are ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 10 /* StringLiteral */:
if (node.hasExtendedUnicodeEscape) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
case 8 /* NumericLiteral */:
if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
case 9 /* BigIntLiteral */:
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 4 /* AssertESNext */;
break;
case 227 /* ForOfStatement */:
// This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
if (node.awaitModifier) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 16 /* AssertES2018 */;
}
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 207 /* YieldExpression */:
// This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
// generator).
- transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */;
+ transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 131072 /* ContainsYield */;
break;
case 120 /* AnyKeyword */:
case 135 /* NumberKeyword */:
@@ -30476,115 +30754,93 @@
case 182 /* LiteralType */:
case 247 /* NamespaceExportDeclaration */:
// Types and signatures are TypeScript syntax, and exclude all other facts.
- transformFlags = 3 /* AssertTypeScript */;
- excludeFlags = -3 /* TypeExcludes */;
+ transformFlags = 1 /* AssertTypeScript */;
+ excludeFlags = -2 /* TypeExcludes */;
break;
case 149 /* ComputedPropertyName */:
// Even though computed property names are ES6, we don't treat them as such.
// This is so that they can flow through PropertyName transforms unaffected.
// Instead, we mark the container as ES6, so that it can properly handle the transform.
- transformFlags |= 524288 /* ContainsComputedPropertyName */;
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- // A computed method name like `[this.getName()](x: string) { ... }` needs to
- // distinguish itself from the normal case of a method body containing `this`:
- // `this` inside a method doesn't need to be rewritten (the method provides `this`),
- // whereas `this` inside a computed name *might* need to be rewritten if the class/object
- // is inside an arrow function:
- // `_this = this; () => class K { [_this.getName()]() { ... } }`
- // To make this distinction, use ContainsLexicalThisInComputedPropertyName
- // instead of ContainsLexicalThis for computed property names
- transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */;
- }
+ transformFlags |= 16384 /* ContainsComputedPropertyName */;
break;
case 208 /* SpreadElement */:
- transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */;
+ transformFlags |= 128 /* AssertES2015 */ | 4096 /* ContainsRestOrSpread */;
break;
case 277 /* SpreadAssignment */:
- transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */;
+ transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */;
break;
case 98 /* SuperKeyword */:
// This node is ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */;
- excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super`
+ transformFlags |= 128 /* AssertES2015 */;
+ excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super`
break;
case 100 /* ThisKeyword */:
// Mark this node and its ancestors as containing a lexical `this` keyword.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 2048 /* ContainsLexicalThis */;
break;
case 184 /* ObjectBindingPattern */:
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */;
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */;
}
- excludeFlags = 637666625 /* BindingPatternExcludes */;
+ excludeFlags = 536875008 /* BindingPatternExcludes */;
break;
case 185 /* ArrayBindingPattern */:
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- excludeFlags = 637666625 /* BindingPatternExcludes */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */;
+ excludeFlags = 536875008 /* BindingPatternExcludes */;
break;
case 186 /* BindingElement */:
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
if (node.dotDotDotToken) {
- transformFlags |= 131072 /* ContainsRestOrSpread */;
+ transformFlags |= 4096 /* ContainsRestOrSpread */;
}
break;
case 152 /* Decorator */:
// This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */;
break;
case 188 /* ObjectLiteralExpression */:
- excludeFlags = 638358849 /* ObjectLiteralExcludes */;
- if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) {
+ excludeFlags = 536896512 /* ObjectLiteralExcludes */;
+ if (subtreeFlags & 16384 /* ContainsComputedPropertyName */) {
// If an ObjectLiteralExpression contains a ComputedPropertyName, then it
// is an ES6 node.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
- }
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
// If an ObjectLiteralExpression contains a spread element, then it
- // is an ES next node.
- transformFlags |= 8 /* AssertESNext */;
+ // is an ES2018 node.
+ transformFlags |= 16 /* AssertES2018 */;
}
break;
case 187 /* ArrayLiteralExpression */:
- case 192 /* NewExpression */:
- excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */;
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
- // If the this node contains a SpreadExpression, then it is an ES6
- // node.
- transformFlags |= 192 /* AssertES2015 */;
- }
+ excludeFlags = 536875008 /* ArrayLiteralOrCallOrNewExcludes */;
break;
case 223 /* DoStatement */:
case 224 /* WhileStatement */:
case 225 /* ForStatement */:
case 226 /* ForInStatement */:
// A loop containing a block scoped binding *may* need to be transformed from ES6.
- if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) {
- transformFlags |= 192 /* AssertES2015 */;
+ if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
- case 279 /* SourceFile */:
- if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) {
- transformFlags |= 192 /* AssertES2015 */;
- }
+ case 284 /* SourceFile */:
break;
case 230 /* ReturnStatement */:
- // Return statements may require an `await` in ESNext.
- transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */;
+ // Return statements may require an `await` in ES2018.
+ transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */ | 16 /* AssertES2018 */;
break;
case 228 /* ContinueStatement */:
case 229 /* BreakStatement */:
- transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */;
+ transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */;
break;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
return transformFlags & ~excludeFlags;
}
+ function propagatePropertyNameFlags(node, transformFlags) {
+ return transformFlags | (node.transformFlags & 2048 /* PropertyNamePropagatingFlags */);
+ }
/**
* Gets the transform flags to exclude when unioning the transform flags of a subtree.
*
@@ -30594,33 +30850,33 @@
*/
function getTransformFlagsSubtreeExclusions(kind) {
if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) {
- return -3 /* TypeExcludes */;
+ return -2 /* TypeExcludes */;
}
switch (kind) {
case 191 /* CallExpression */:
case 192 /* NewExpression */:
case 187 /* ArrayLiteralExpression */:
- return 637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return 536875008 /* ArrayLiteralOrCallOrNewExcludes */;
case 244 /* ModuleDeclaration */:
- return 647001409 /* ModuleExcludes */;
+ return 537168896 /* ModuleExcludes */;
case 151 /* Parameter */:
- return 637535553 /* ParameterExcludes */;
+ return 536870912 /* ParameterExcludes */;
case 197 /* ArrowFunction */:
- return 653604161 /* ArrowFunctionExcludes */;
+ return 537371648 /* ArrowFunctionExcludes */;
case 196 /* FunctionExpression */:
case 239 /* FunctionDeclaration */:
- return 653620545 /* FunctionExcludes */;
+ return 537373696 /* FunctionExcludes */;
case 238 /* VariableDeclarationList */:
- return 639894849 /* VariableDeclarationListExcludes */;
+ return 536944640 /* VariableDeclarationListExcludes */;
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
- return 638121281 /* ClassExcludes */;
+ return 536888320 /* ClassExcludes */;
case 157 /* Constructor */:
- return 653616449 /* ConstructorExcludes */;
+ return 537372672 /* ConstructorExcludes */;
case 156 /* MethodDeclaration */:
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
- return 653616449 /* MethodOrAccessorExcludes */;
+ return 537372672 /* MethodOrAccessorExcludes */;
case 120 /* AnyKeyword */:
case 135 /* NumberKeyword */:
case 146 /* BigIntKeyword */:
@@ -30638,25 +30894,25 @@
case 162 /* IndexSignature */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- return -3 /* TypeExcludes */;
+ return -2 /* TypeExcludes */;
case 188 /* ObjectLiteralExpression */:
- return 638358849 /* ObjectLiteralExcludes */;
+ return 536896512 /* ObjectLiteralExcludes */;
case 274 /* CatchClause */:
- return 637797697 /* CatchClauseExcludes */;
+ return 536879104 /* CatchClauseExcludes */;
case 184 /* ObjectBindingPattern */:
case 185 /* ArrayBindingPattern */:
- return 637666625 /* BindingPatternExcludes */;
+ return 536875008 /* BindingPatternExcludes */;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
case 195 /* ParenthesizedExpression */:
case 98 /* SuperKeyword */:
- return 536872257 /* OuterExpressionExcludes */;
+ return 536870912 /* OuterExpressionExcludes */;
case 189 /* PropertyAccessExpression */:
case 190 /* ElementAccessExpression */:
- return 570426689 /* PropertyAccessExcludes */;
+ return 536870912 /* PropertyAccessExcludes */;
default:
- return 637535553 /* NodeExcludes */;
+ return 536870912 /* NodeExcludes */;
}
}
ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
@@ -30905,6 +31161,7 @@
var enumCount = 0;
var instantiationDepth = 0;
var constraintDepth = 0;
+ var currentNode;
var emptySymbols = ts.createSymbolTable();
var identityMapper = ts.identity;
var compilerOptions = host.getCompilerOptions();
@@ -30921,8 +31178,14 @@
var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
var emitResolver = createResolver();
var nodeBuilder = createNodeBuilder();
+ var globals = ts.createSymbolTable();
var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
undefinedSymbol.declarations = [];
+ var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
+ globalThisSymbol.exports = globals;
+ globalThisSymbol.valueDeclaration = ts.createNode(72 /* Identifier */);
+ globalThisSymbol.valueDeclaration.escapedText = "globalThis";
+ globals.set(globalThisSymbol.escapedName, globalThisSymbol);
var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
var requireSymbol = createSymbol(4 /* Property */, "require");
/** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
@@ -31052,11 +31315,13 @@
isContextSensitive: isContextSensitive,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 0 /* Normal */);
},
getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */);
},
+ getExpandedParameters: getExpandedParameters,
+ hasEffectiveRestParameter: hasEffectiveRestParameter,
getConstantValue: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
return node ? getConstantValue(node) : undefined;
@@ -31118,6 +31383,8 @@
getNeverType: function () { return neverType; },
isSymbolAccessible: isSymbolAccessible,
getObjectFlags: ts.getObjectFlags,
+ isArrayType: isArrayType,
+ isTupleType: isTupleType,
isArrayLikeType: isArrayLikeType,
isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
@@ -31133,9 +31400,9 @@
getAccessibleSymbolChain: getAccessibleSymbolChain,
getTypePredicateOfSignature: getTypePredicateOfSignature,
resolveExternalModuleSymbol: resolveExternalModuleSymbol,
- tryGetThisTypeAt: function (node) {
+ tryGetThisTypeAt: function (node, includeGlobalThis) {
node = ts.getParseTreeNode(node);
- return node && tryGetThisTypeAt(node);
+ return node && tryGetThisTypeAt(node, includeGlobalThis);
},
getTypeArgumentConstraint: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
@@ -31182,10 +31449,10 @@
},
getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
};
- function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) {
+ function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
apparentArgumentCount = argumentCount;
- var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined;
+ var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
apparentArgumentCount = undefined;
return res;
}
@@ -31194,6 +31461,7 @@
var intersectionTypes = ts.createMap();
var literalTypes = ts.createMap();
var indexedAccessTypes = ts.createMap();
+ var conditionalTypes = ts.createMap();
var evolvingArrayTypes = [];
var undefinedProperties = ts.createMap();
var unknownSymbol = createSymbol(4 /* Property */, "unknown");
@@ -31204,9 +31472,9 @@
var errorType = createIntrinsicType(1 /* Any */, "error");
var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
- var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined");
+ var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */);
var nullType = createIntrinsicType(65536 /* Null */, "null");
- var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null");
+ var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */);
var stringType = createIntrinsicType(4 /* String */, "string");
var numberType = createIntrinsicType(8 /* Number */, "number");
var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
@@ -31232,6 +31500,7 @@
var voidType = createIntrinsicType(16384 /* Void */, "void");
var neverType = createIntrinsicType(131072 /* Never */, "never");
var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
+ var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */);
var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
@@ -31248,7 +31517,7 @@
var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
// The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
// in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
- anyFunctionType.flags |= 536870912 /* ContainsAnyFunctionType */;
+ anyFunctionType.objectFlags |= 524288 /* NonInferrableType */;
var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
@@ -31262,7 +31531,6 @@
var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
- var globals = ts.createSymbolTable();
/** Key is "/path/to/a.ts|/path/to/b.ts". */
var amalgamatedDuplicates;
var reverseMappedCache = ts.createMap();
@@ -31461,9 +31729,11 @@
var CheckMode;
(function (CheckMode) {
CheckMode[CheckMode["Normal"] = 0] = "Normal";
- CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive";
+ CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
- CheckMode[CheckMode["Contextual"] = 3] = "Contextual";
+ CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
+ CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
+ CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
})(CheckMode || (CheckMode = {}));
var CallbackCheck;
(function (CallbackCheck) {
@@ -31550,18 +31820,6 @@
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)
@@ -31741,7 +31999,7 @@
err.relatedInformation = err.relatedInformation || [];
if (ts.length(err.relatedInformation) >= 5)
continue;
- addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here));
+ ts.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) {
@@ -31819,7 +32077,7 @@
return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
}
function isGlobalSourceFile(node) {
- return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
+ return node.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning) {
@@ -31993,7 +32251,7 @@
// - 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 & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) {
+ if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 296 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -32035,14 +32293,14 @@
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
isInExternalModule = true;
// falls through
case 244 /* ModuleDeclaration */:
var moduleExports = getSymbolOfNode(location).exports;
- if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) {
+ if (location.kind === 284 /* 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 */)) {
@@ -32210,12 +32468,18 @@
// @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
// }
//
- if (location.parent && ts.isClassElement(location.parent)) {
+ // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
+ //
+ // type T = number;
+ // declare function y(x: T): any;
+ // @param(1 as T) // <-- T should resolve to the type alias outside of class C
+ // class C<T> {}
+ if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 240 /* ClassDeclaration */)) {
location = location.parent;
}
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
// js type aliases do not resolve names from their host, so skip past it
location = ts.getJSDocHost(location);
break;
@@ -32234,7 +32498,7 @@
}
if (!result) {
if (lastLocation) {
- ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */);
+ ts.Debug.assert(lastLocation.kind === 284 /* SourceFile */);
if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
return lastLocation.symbol;
}
@@ -32257,7 +32521,8 @@
!checkAndReportErrorForExtendingInterface(errorLocation) &&
!checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
!checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
- !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) {
+ !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
+ !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
var suggestion = void 0;
if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
@@ -32265,7 +32530,7 @@
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));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
}
}
}
@@ -32422,6 +32687,16 @@
}
return false;
}
+ function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
+ if (meaning & (67897832 /* Type */ & ~1920 /* Namespace */)) {
+ var symbol = resolveSymbol(resolveName(errorLocation, name, ~67897832 /* Type */ & 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
+ error(errorLocation, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here, ts.unescapeLeadingUnderscores(name));
+ return true;
+ }
+ }
+ return false;
+ }
function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) {
if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") {
@@ -32430,7 +32705,7 @@
}
var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
- var message = (name === "Promise" || name === "Symbol")
+ var message = isES2015OrLaterConstructorName(name)
? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later
: ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
@@ -32439,6 +32714,18 @@
}
return false;
}
+ function isES2015OrLaterConstructorName(n) {
+ switch (n) {
+ case "Promise":
+ case "Symbol":
+ case "Map":
+ case "WeakMap":
+ case "Set":
+ case "WeakSet":
+ return true;
+ }
+ return false;
+ }
function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) {
var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
@@ -32481,7 +32768,7 @@
}
}
if (diagnosticMessage) {
- addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
+ ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
}
}
}
@@ -32665,7 +32952,7 @@
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));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
}
}
else {
@@ -32985,22 +33272,14 @@
return undefined;
}
if (moduleNotFoundError) {
- // For relative paths, see if this was possibly a projectReference redirect
- if (ts.pathIsRelative(moduleReference)) {
- var sourceFile_1 = ts.getSourceFileOfNode(location);
- var redirects = sourceFile_1.redirectedReferences;
- if (redirects) {
- var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName));
- for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) {
- var ext = _a[_i];
- var probePath = normalizedTargetPath + ext;
- if (redirects.indexOf(probePath) >= 0) {
- error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath);
+ // See if this was possibly a projectReference redirect
+ if (resolvedModule) {
+ var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
+ if (redirect) {
+ error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
return undefined;
}
}
- }
- }
if (resolutionDiagnostic) {
error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
}
@@ -33067,7 +33346,7 @@
function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) {
var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
if (!dontResolveAlias && symbol) {
- if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) {
+ if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 284 /* SourceFile */)) {
var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
? "allowSyntheticDefaultImports"
: "esModuleInterop";
@@ -33340,9 +33619,11 @@
result.id = typeCount;
return result;
}
- function createIntrinsicType(kind, intrinsicName) {
+ function createIntrinsicType(kind, intrinsicName, objectFlags) {
+ if (objectFlags === void 0) { objectFlags = 0; }
var type = createType(kind);
type.intrinsicName = intrinsicName;
+ type.objectFlags = objectFlags;
return type;
}
function createBooleanType(trueFalseTypes) {
@@ -33413,7 +33694,7 @@
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
@@ -33653,10 +33934,10 @@
return node && getSymbolOfNode(node);
}
function hasExternalModuleSymbol(declaration) {
- return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isAmbientModule(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
- return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
var aliasesToMakeVisible;
@@ -34025,8 +34306,8 @@
context.inferTypeParameters = type.root.inferTypeParameters;
var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
context.inferTypeParameters = saveInferTypeParameters;
- var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context);
- var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context);
+ var trueTypeNode = typeToTypeNodeHelper(type.trueType, context);
+ var falseTypeNode = typeToTypeNodeHelper(type.falseType, context);
context.approximateLength += 15;
return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
}
@@ -34113,7 +34394,7 @@
var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
(symbol.parent || // is exported function symbol
ts.forEach(symbol.declarations, function (declaration) {
- return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
+ return declaration.parent.kind === 284 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
// typeof is allowed only for static/non local functions
@@ -34153,13 +34434,14 @@
}
function typeReferenceToTypeNode(type) {
var typeArguments = type.typeArguments || ts.emptyArray;
- if (type.target === globalArrayType) {
+ if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
if (context.flags & 2 /* WriteArrayAsGenericType */) {
var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
- return ts.createTypeReferenceNode("Array", [typeArgumentNode]);
+ return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
}
var elementType = typeToTypeNodeHelper(typeArguments[0], context);
- return ts.createArrayTypeNode(elementType);
+ var arrayType = ts.createArrayTypeNode(elementType);
+ return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, arrayType);
}
else if (type.target.objectFlags & 8 /* Tuple */) {
if (typeArguments.length > 0) {
@@ -34172,11 +34454,13 @@
ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
ts.createOptionalTypeNode(tupleConstituentNodes[i]);
}
- return ts.createTupleTypeNode(tupleConstituentNodes);
+ var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes);
+ return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
}
}
if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
- return ts.createTupleTypeNode([]);
+ var tupleTypeNode = ts.createTupleTypeNode([]);
+ return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
}
context.encounteredError = true;
return undefined; // TODO: GH#18217
@@ -34340,7 +34624,7 @@
context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
context.enclosingDeclaration = saveEnclosingDeclaration;
var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined;
- if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) {
+ if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
var signatures = getSignaturesOfType(propertyType, 0 /* Call */);
for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
var signature = signatures_1[_i];
@@ -34476,7 +34760,7 @@
var savedContextFlags = context.flags;
context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
- type.symbol.declarations[0] &&
+ type.symbol.declarations && type.symbol.declarations[0] &&
ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
typeParameterShadowsNameInScope(type, context);
var name = shouldUseGeneratedName
@@ -34495,7 +34779,7 @@
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */);
if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
- parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */);
+ parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 304 /* JSDocParameterTag */);
}
var parameterType = getTypeOfSymbol(parameterSymbol);
if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
@@ -34653,7 +34937,7 @@
return top;
}
function getSpecifierForModuleSymbol(symbol, context) {
- var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */);
+ var file = ts.getDeclarationOfKind(symbol, 284 /* SourceFile */);
if (file && file.moduleName !== undefined) {
// Use the amd name if it is available
return file.moduleName;
@@ -34906,7 +35190,7 @@
ts.isExternalModuleAugmentation(node.parent.parent);
}
function isDefaultBindingContext(location) {
- return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location);
+ return location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location);
}
function getNameOfSymbolFromNameType(symbol, context) {
var nameType = symbol.nameType;
@@ -34983,8 +35267,8 @@
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* 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));
@@ -35011,7 +35295,7 @@
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 !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
+ !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 284 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
return isGlobalSourceFile(parent);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
@@ -35053,7 +35337,7 @@
// Type parameters are always visible
case 150 /* TypeParameter */:
// Source file and namespace export are always visible
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 247 /* NamespaceExportDeclaration */:
return true;
// Export assignments do not create name bindings outside the module
@@ -35232,7 +35516,7 @@
if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
&& !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
&& isSpreadableProperty(prop)) {
- members.set(prop.escapedName, getSpreadSymbol(prop));
+ members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
}
}
var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
@@ -35301,17 +35585,8 @@
function getTypeForBindingElement(declaration) {
var pattern = declaration.parent;
var parentType = getTypeForBindingElementParent(pattern.parent);
- // If parent has the unknown (error) type, then so does this binding element
- if (parentType === errorType) {
- return errorType;
- }
- // If no type was specified or inferred for parent,
- // infer from the initializer of the binding element if one is present.
- // Otherwise, go with the undefined type of the parent.
- if (!parentType) {
- return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType;
- }
- if (isTypeAny(parentType)) {
+ // If no type or an any type was inferred for parent, infer that for the binding element
+ if (!parentType || isTypeAny(parentType)) {
return parentType;
}
// Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
@@ -35393,6 +35668,11 @@
if (optional === void 0) { optional = true; }
return strictNullChecks && optional ? getOptionalType(type) : type;
}
+ function isParameterOfContextuallyTypedFunction(node) {
+ return node.kind === 151 /* Parameter */ &&
+ (node.parent.kind === 196 /* FunctionExpression */ || node.parent.kind === 197 /* ArrowFunction */) &&
+ !!getContextualType(node.parent);
+ }
// Return the inferred type for a variable, parameter, or property declaration
function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
// A variable declared in a for..in statement is of type string, or of type keyof T when the
@@ -35468,8 +35748,9 @@
return containerObjectType;
}
}
- // Use the type of the initializer expression if one is present
- if (declaration.initializer) {
+ // Use the type of the initializer expression if one is present and the declaration is
+ // not a parameter of a contextually typed function
+ if (declaration.initializer && !isParameterOfContextuallyTypedFunction(declaration)) {
var type = checkDeclarationInitializer(declaration);
return addOptionality(type, isOptional);
}
@@ -35478,8 +35759,9 @@
// I.e <Elem attr /> is sugar for <Elem attr={true} />
return trueType;
}
- // If the declaration specifies a binding pattern, use the type implied by the binding pattern
- if (ts.isBindingPattern(declaration.name)) {
+ // If the declaration specifies a binding pattern and is not a parameter of a contextually
+ // typed function, use the type implied by the binding pattern
+ if (ts.isBindingPattern(declaration.name) && !isParameterOfContextuallyTypedFunction(declaration)) {
return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
}
// No type specified and nothing can be inferred
@@ -35535,7 +35817,7 @@
definedInConstructor = true;
}
}
- var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217
+ var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
type = getUnionType(sourceTypes, 2 /* Subtype */);
}
var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
@@ -35686,7 +35968,7 @@
function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
var members = ts.createSymbolTable();
var stringIndexInfo;
- var objectFlags = 128 /* ObjectLiteral */;
+ var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
ts.forEach(pattern.elements, function (e) {
var name = e.propertyName || e.name;
if (e.dotDotDotToken) {
@@ -35707,7 +35989,6 @@
members.set(symbol.escapedName, symbol);
});
var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
- result.flags |= 268435456 /* ContainsObjectLiteral */;
result.objectFlags |= objectFlags;
if (includePatternInType) {
result.pattern = pattern;
@@ -35791,7 +36072,16 @@
}
function getTypeOfVariableOrParameterOrProperty(symbol) {
var links = getSymbolLinks(symbol);
- return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol));
+ if (!links.type) {
+ var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
+ // For a contextually typed parameter it is possible that a type has already
+ // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
+ // to preserve this type.
+ if (!links.type) {
+ links.type = type;
+ }
+ }
+ return links.type;
}
function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
// Handle prototype property
@@ -35824,19 +36114,19 @@
}
return type_1;
}
- if (declaration.kind === 254 /* ExportAssignment */) {
- return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
- }
// Handle variable, parameter or property
if (!pushTypeResolution(symbol, 0 /* Type */)) {
// Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
if (symbol.flags & 512 /* ValueModule */) {
return getTypeOfFuncClassEnumModule(symbol);
}
- return errorType;
+ return reportCircularityError(symbol);
}
var type;
- if (ts.isInJSFile(declaration) &&
+ if (declaration.kind === 254 /* ExportAssignment */) {
+ type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
+ }
+ else if (ts.isInJSFile(declaration) &&
(ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) {
type = getWidenedTypeFromAssignmentDeclaration(symbol);
}
@@ -35891,7 +36181,7 @@
if (symbol.flags & 512 /* ValueModule */) {
return getTypeOfFuncClassEnumModule(symbol);
}
- type = reportCircularityError(symbol);
+ return reportCircularityError(symbol);
}
return type;
}
@@ -36069,15 +36359,19 @@
return links.type;
}
function reportCircularityError(symbol) {
+ var declaration = symbol.valueDeclaration;
// Check if variable has type annotation that circularly references the variable itself
- if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) {
+ if (ts.getEffectiveTypeAnnotationNode(declaration)) {
error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
return errorType;
}
- // Otherwise variable has initializer that circularly references the variable itself
- if (noImplicitAny) {
+ // Check if variable has initializer that circularly references the variable itself
+ if (noImplicitAny && (declaration.kind !== 151 /* Parameter */ || declaration.initializer)) {
error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
}
+ // Circularities could also result from parameters in function expressions that end up
+ // having themselves as contextual types following type argument inference. In those cases
+ // we have already reported an implicit any error so we don't report anything here.
return anyType;
}
function getTypeOfSymbol(symbol) {
@@ -36153,15 +36447,15 @@
case 155 /* MethodSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 308 /* JSDocTemplateTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 181 /* MappedType */:
case 175 /* ConditionalType */:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -36282,7 +36576,7 @@
ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
}
}
- addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
+ ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
}
return type.resolvedBaseConstructorType = errorType;
}
@@ -36293,7 +36587,7 @@
function getBaseTypes(type) {
if (!type.resolvedBaseTypes) {
if (type.objectFlags & 8 /* Tuple */) {
- type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))];
+ type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)];
}
else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
if (type.symbol.flags & 32 /* Class */) {
@@ -36658,7 +36952,7 @@
}
return false;
}
- /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */
+ /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
function isThislessTypeParameter(node) {
var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
return !constraint || isThislessType(constraint);
@@ -36701,6 +36995,8 @@
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
case 157 /* Constructor */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
return isThislessFunctionLikeDeclaration(declaration);
}
}
@@ -37032,8 +37328,18 @@
return sig;
}
function cloneSignature(sig) {
- return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
+ var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
/*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes);
+ result.target = sig.target;
+ result.mapper = sig.mapper;
+ return result;
+ }
+ function createUnionSignature(signature, unionSignatures) {
+ var result = cloneSignature(signature);
+ result.unionSignatures = unionSignatures;
+ result.target = undefined;
+ result.mapper = undefined;
+ return result;
}
function getExpandedParameters(sig) {
if (sig.hasRestParameter) {
@@ -37142,9 +37448,8 @@
var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */);
thisParameter = createSymbolWithType(signature.thisParameter, thisType);
}
- s = cloneSignature(signature);
+ s = createUnionSignature(signature, unionSignatures);
s.thisParameter = thisParameter;
- s.unionSignatures = unionSignatures;
}
(result || (result = [])).push(s);
}
@@ -37259,13 +37564,22 @@
function unionSpreadIndexInfos(info1, info2) {
return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
}
- function includeMixinType(type, types, index) {
+ function findMixins(types) {
+ var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
+ var mixinFlags = ts.map(types, isMixinConstructorType);
+ if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
+ var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
+ mixinFlags[firstMixinIndex] = false;
+ }
+ return mixinFlags;
+ }
+ function includeMixinType(type, types, mixinFlags, index) {
var mixedTypes = [];
for (var i = 0; i < types.length; i++) {
if (i === index) {
mixedTypes.push(type);
}
- else if (isMixinConstructorType(types[i])) {
+ else if (mixinFlags[i]) {
mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
}
}
@@ -37279,7 +37593,8 @@
var stringIndexInfo;
var numberIndexInfo;
var types = type.types;
- var mixinCount = ts.countWhere(types, isMixinConstructorType);
+ var mixinFlags = findMixins(types);
+ var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
var _loop_6 = function (i) {
var t = type.types[i];
// When an intersection type contains mixin constructor types, the construct signatures from
@@ -37287,12 +37602,12 @@
// other construct signatures in the intersection type. For example, the intersection type
// '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
// 'new(s: string) => A & B'.
- if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) {
+ if (!mixinFlags[i]) {
var signatures = getSignaturesOfType(t, 1 /* Construct */);
if (signatures.length && mixinCount > 0) {
signatures = ts.map(signatures, function (s) {
var clone = cloneSignature(s);
- clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i);
+ clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
return clone;
});
}
@@ -37336,6 +37651,15 @@
var stringIndexInfo = void 0;
if (symbol.exports) {
members = getExportsOfSymbol(symbol);
+ if (symbol === globalThisSymbol) {
+ var varsOnly_1 = ts.createMap();
+ members.forEach(function (p) {
+ if (!(p.flags & 418 /* BlockScoped */)) {
+ varsOnly_1.set(p.escapedName, p);
+ }
+ });
+ members = varsOnly_1;
+ }
}
setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
if (symbol.flags & 32 /* Class */) {
@@ -37635,7 +37959,7 @@
var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
- return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected);
+ return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
});
}
function getAllPossiblePropertiesOfTypes(types) {
@@ -37668,6 +37992,9 @@
return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
}
function getConstraintOfIndexedAccess(type) {
+ return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
+ }
+ function getConstraintFromIndexedAccess(type) {
var objectType = getConstraintOfType(type.objectType) || type.objectType;
if (objectType !== type.objectType) {
var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType);
@@ -37680,13 +38007,13 @@
}
function getDefaultConstraintOfConditionalType(type) {
if (!type.resolvedDefaultConstraint) {
- var rootTrueType = type.root.trueType;
- var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */)
- ? rootTrueType
- : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */
- ? rootTrueType.typeVariable
- : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]);
- type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]);
+ // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
+ // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
+ // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
+ // in effect treating `any` like `never` rather than `unknown` in this location.
+ var trueConstraint = getInferredTrueTypeFromConditionalType(type);
+ var falseConstraint = type.falseType;
+ type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
}
return type.resolvedDefaultConstraint;
}
@@ -37696,7 +38023,13 @@
// with its constraint. We do this because if the constraint is a union type it will be distributed
// over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
// removes 'undefined' from T.
- if (type.root.isDistributive) {
+ // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
+ // as the constraint for all type params (check type included) have been replace with `unknown`, which
+ // is going to produce even more false positive/negative results than the distribute constraint already does.
+ // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
+ // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
+ // likely doesn't need to exist.
+ if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
var simplified = getSimplifiedType(type.checkType);
var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
if (constraint && constraint !== type.checkType) {
@@ -37709,9 +38042,12 @@
}
return undefined;
}
- function getConstraintOfConditionalType(type) {
+ function getConstraintFromConditionalType(type) {
return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
}
+ function getConstraintOfConditionalType(type) {
+ return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
+ }
function getUnionConstraintOfIntersection(type, targetIsUnion) {
var constraints;
var hasDisjointDomainType = false;
@@ -37785,18 +38121,31 @@
if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
return circularConstraintType;
}
- if (constraintDepth === 50) {
+ if (constraintDepth >= 50) {
// We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
// very high likelyhood we're dealing with an infinite generic type that perpetually generates
// new type identities as we descend into it. We stop the recursion here and mark this type
// and the outer types as having circular constraints.
+ error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
nonTerminating = true;
return t.immediateBaseConstraint = noConstraintType;
}
constraintDepth++;
var result = computeBaseConstraint(getSimplifiedType(t));
constraintDepth--;
- if (!popTypeResolution() || nonTerminating) {
+ if (!popTypeResolution()) {
+ if (t.flags & 262144 /* TypeParameter */) {
+ var errorNode = getConstraintDeclaration(t);
+ if (errorNode) {
+ var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
+ if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
+ }
+ }
+ }
+ result = circularConstraintType;
+ }
+ if (nonTerminating) {
result = circularConstraintType;
}
t.immediateBaseConstraint = result || noConstraintType;
@@ -37838,8 +38187,11 @@
return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined;
}
if (t.flags & 16777216 /* Conditional */) {
- var constraint = getConstraintOfConditionalType(t);
- return constraint && getBaseConstraint(constraint);
+ var constraint = getConstraintFromConditionalType(t);
+ constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
+ var result = constraint && getBaseConstraint(constraint);
+ constraintDepth--;
+ return result;
}
if (t.flags & 33554432 /* Substitution */) {
return getBaseConstraint(t.substitute);
@@ -37900,7 +38252,7 @@
var typeVariable = getHomomorphicTypeVariable(type);
if (typeVariable) {
var constraint = getConstraintOfTypeParameter(typeVariable);
- if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) {
+ if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
var mapper = makeUnaryTypeMapper(typeVariable, constraint);
return instantiateType(type, combineTypeMappers(mapper, type.mapper));
}
@@ -37918,7 +38270,7 @@
t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
t.flags & 132 /* StringLike */ ? globalStringType :
t.flags & 296 /* NumberLike */ ? globalNumberType :
- t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) :
+ t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ESNext */) :
t.flags & 528 /* BooleanLike */ ? globalBooleanType :
t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
@@ -37926,7 +38278,7 @@
t;
}
function createUnionOrIntersectionProperty(containingType, name) {
- var props;
+ var propSet = ts.createMap();
var indexTypes;
var isUnion = containingType.flags & 1048576 /* Union */;
var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0;
@@ -37942,7 +38294,10 @@
var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
if (prop && !(modifiers & excludeModifiers)) {
commonFlags &= prop.flags;
- props = ts.appendIfUnique(props, prop);
+ var id = "" + getSymbolId(prop);
+ if (!propSet.has(id)) {
+ propSet.set(id, prop);
+ }
checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
(!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) |
(modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) |
@@ -37964,9 +38319,10 @@
}
}
}
- if (!props) {
+ if (!propSet.size) {
return undefined;
}
+ var props = ts.arrayFrom(propSet.values());
if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) {
return props[0];
}
@@ -38138,10 +38494,10 @@
function isJSDocOptionalParameter(node) {
return ts.isInJSFile(node) && (
// node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
- node.type && node.type.kind === 288 /* JSDocOptionalType */
+ node.type && node.type.kind === 293 /* JSDocOptionalType */
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -38175,7 +38531,7 @@
return false;
}
var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}
function createIdentifierTypePredicate(parameterName, parameterIndex, type) {
return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
@@ -38409,32 +38765,23 @@
}
}
signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
- createTypePredicateFromTypePredicateNode(type, signature.declaration) :
+ createTypePredicateFromTypePredicateNode(type, signature) :
jsdocPredicate || noTypePredicate;
}
ts.Debug.assert(!!signature.resolvedTypePredicate);
}
return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
}
- function createTypePredicateFromTypePredicateNode(node, func) {
+ function createTypePredicateFromTypePredicateNode(node, signature) {
var parameterName = node.parameterName;
var type = getTypeFromTypeNode(node.type);
if (parameterName.kind === 72 /* Identifier */) {
- return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type);
+ return createIdentifierTypePredicate(parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), 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 === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) {
- return i;
- }
- }
- return -1;
- }
function getReturnTypeOfSignature(signature) {
if (!signature.resolvedReturnType) {
if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
@@ -38506,8 +38853,19 @@
}
return undefined;
}
- function getSignatureInstantiation(signature, typeArguments, isJavascript) {
- return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ if (inferredTypeParameters) {
+ var returnSignature = getSingleCallSignature(getReturnTypeOfSignature(instantiatedSignature));
+ if (returnSignature) {
+ var newReturnSignature = cloneSignature(returnSignature);
+ newReturnSignature.typeParameters = inferredTypeParameters;
+ var newInstantiatedSignature = cloneSignature(instantiatedSignature);
+ newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
+ return newInstantiatedSignature;
+ }
+ }
+ return instantiatedSignature;
}
function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
@@ -38702,10 +39060,10 @@
for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
var type = types_5[_i];
if (!(type.flags & excludeKinds)) {
- result |= type.flags;
+ result |= ts.getObjectFlags(type);
}
}
- return result & 939524096 /* PropagatingFlags */;
+ return result & 917504 /* PropagatingFlags */;
}
function createTypeReference(target, typeArguments) {
var id = getTypeListId(typeArguments);
@@ -38713,7 +39071,7 @@
if (!type) {
type = createObjectType(4 /* Reference */, target.symbol);
target.instantiations.set(id, type);
- type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
+ type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
type.target = target;
type.typeArguments = typeArguments;
}
@@ -38879,7 +39237,7 @@
}
function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
- if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
+ if (symbol.valueDeclaration && symbol.valueDeclaration.parent && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
if (jsdocType) {
return jsdocType;
@@ -38900,6 +39258,9 @@
}
}
function getSubstitutionType(typeVariable, substitute) {
+ if (substitute.flags & 3 /* AnyOrUnknown */) {
+ return typeVariable;
+ }
var result = createType(33554432 /* Substitution */);
result.typeVariable = typeVariable;
result.substitute = substitute;
@@ -38915,7 +39276,7 @@
}
function getConstrainedTypeVariable(typeVariable, node) {
var constraints;
- while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) {
+ while (node && !ts.isStatement(node) && node.kind !== 296 /* JSDocComment */) {
var parent = node.parent;
if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) {
var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
@@ -39147,19 +39508,19 @@
function createIterableIteratorType(iteratedType) {
return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]);
}
- function createArrayType(elementType) {
- return createTypeFromGenericGlobalType(globalArrayType, [elementType]);
- }
- function createReadonlyArrayType(elementType) {
- return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]);
+ function createArrayType(elementType, readonly) {
+ return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
}
function getTypeFromArrayTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType));
+ links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType), isReadonlyTypeOperator(node.parent));
}
return links.resolvedType;
}
+ function isReadonlyTypeOperator(node) {
+ return ts.isTypeOperatorNode(node) && node.operator === 133 /* ReadonlyKeyword */;
+ }
// We represent tuple types as type references to synthesized generic interface types created by
// this function. The types are of the form:
//
@@ -39167,7 +39528,7 @@
//
// 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, minLength, hasRestElement, associatedNames) {
+ function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
var typeParameters;
var properties = [];
var maxLength = hasRestElement ? arity - 1 : arity;
@@ -39176,7 +39537,7 @@
for (var i = 0; i < arity; i++) {
var typeParameter = typeParameters[i] = createTypeParameter();
if (i < maxLength) {
- var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i);
+ var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
property.type = typeParameter;
properties.push(property);
}
@@ -39206,25 +39567,27 @@
type.declaredNumberIndexInfo = undefined;
type.minLength = minLength;
type.hasRestElement = hasRestElement;
+ type.readonly = readonly;
type.associatedNames = associatedNames;
return type;
}
- function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) {
- var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
+ function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
+ var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
var type = tupleTypes.get(key);
if (!type) {
- tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames));
+ tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames));
}
return type;
}
- function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) {
+ function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) {
if (minLength === void 0) { minLength = elementTypes.length; }
if (hasRestElement === void 0) { hasRestElement = false; }
+ if (readonly === void 0) { readonly = false; }
var arity = elementTypes.length;
if (arity === 1 && hasRestElement) {
- return createArrayType(elementTypes[0]);
+ return createArrayType(elementTypes[0], readonly);
}
- var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames);
+ var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames);
return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
}
function getTypeFromTupleTypeNode(node) {
@@ -39237,7 +39600,7 @@
var type = getTypeFromTypeNode(n);
return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type;
});
- links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1);
+ links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1, isReadonlyTypeOperator(node.parent));
}
return links.resolvedType;
}
@@ -39247,7 +39610,7 @@
// don't slice off rest element
index = Math.min(index, getTypeReferenceArity(type) - 1);
}
- return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index));
+ return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index));
}
function getTypeFromOptionalTypeNode(node) {
var type = getTypeFromTypeNode(node.type);
@@ -39305,12 +39668,14 @@
// intersections of unit types into 'never' upon construction, but deferring the reduction makes it
// easier to reason about their origin.
if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) {
- includes |= flags & ~939524096 /* ConstructionFlags */;
+ includes |= flags & 1835007 /* IncludesMask */;
+ if (flags & 66846720 /* StructuredOrInstantiable */)
+ includes |= 262144 /* IncludesStructuredOrInstantiable */;
if (type === wildcardType)
- includes |= 268435456 /* Wildcard */;
+ includes |= 4194304 /* IncludesWildcard */;
if (!strictNullChecks && flags & 98304 /* Nullable */) {
- if (!(flags & 134217728 /* ContainsWideningType */))
- includes |= 134217728 /* NonWideningType */;
+ if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */))
+ includes |= 2097152 /* IncludesNonWideningType */;
}
else {
var len = typeSet.length;
@@ -39331,17 +39696,6 @@
}
return includes;
}
- function isSubtypeOfAny(source, targets) {
- for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
- var target = targets_1[_i];
- if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
- !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
- isTypeDerivedFrom(source, target))) {
- return true;
- }
- }
- return false;
- }
function isSetOfLiteralsFromSameEnum(types) {
var first = types[0];
if (first.flags & 1024 /* EnumLiteral */) {
@@ -39356,18 +39710,43 @@
}
return false;
}
- function removeSubtypes(types) {
- if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) {
- return;
+ function removeSubtypes(types, primitivesOnly) {
+ var len = types.length;
+ if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
+ return true;
}
- var i = types.length;
+ var i = len;
+ var count = 0;
while (i > 0) {
i--;
- if (isSubtypeOfAny(types[i], types)) {
+ var source = types[i];
+ for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
+ var target = types_7[_i];
+ if (source !== target) {
+ if (count === 100000) {
+ // After 100000 subtype checks we estimate the remaining amount of work by assuming the
+ // same ratio of checks per element. If the estimated number of remaining type checks is
+ // greater than an upper limit we deem the union type too complex to represent. The
+ // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
+ // caps union types at 5000 unique literal types and 1000 unique object types.
+ var estimatedCount = (count / (len - i)) * len;
+ if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
+ error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
+ return false;
+ }
+ }
+ count++;
+ if (isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
+ !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
+ isTypeDerivedFrom(source, target))) {
ts.orderedRemoveItemAt(types, i);
+ break;
+ }
}
}
}
+ return true;
+ }
function removeRedundantLiteralTypes(types, includes) {
var i = types.length;
while (i > 0) {
@@ -39402,25 +39781,27 @@
var includes = addTypesToUnion(typeSet, 0, types);
if (unionReduction !== 0 /* None */) {
if (includes & 3 /* AnyOrUnknown */) {
- return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType;
+ return includes & 1 /* Any */ ? includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
}
switch (unionReduction) {
case 1 /* Literal */:
- if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) {
+ if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
removeRedundantLiteralTypes(typeSet, includes);
}
break;
case 2 /* Subtype */:
- removeSubtypes(typeSet);
+ if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
+ return errorType;
+ }
break;
}
if (typeSet.length === 0) {
- return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType :
- includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType :
+ return includes & 65536 /* Null */ ? includes & 2097152 /* IncludesNonWideningType */ ? nullType : nullWideningType :
+ includes & 32768 /* Undefined */ ? includes & 2097152 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
neverType;
}
}
- return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments);
+ return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments);
}
function getUnionTypePredicate(signatures) {
var first;
@@ -39457,7 +39838,7 @@
: !ts.isIdentifierTypePredicate(b);
}
// This function assumes the constituent type list is sorted and deduplicated.
- function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) {
+ function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
if (types.length === 0) {
return neverType;
}
@@ -39467,11 +39848,10 @@
var id = getTypeListId(types);
var type = unionTypes.get(id);
if (!type) {
- var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
- type = createType(1048576 /* Union */ | propagatedFlags);
+ type = createType(1048576 /* Union */);
unionTypes.set(id, type);
+ type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
type.types = types;
- type.primitiveTypesOnly = primitiveTypesOnly;
/*
Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
@@ -39497,16 +39877,16 @@
return addTypesToIntersection(typeSet, includes, type.types);
}
if (isEmptyAnonymousObjectType(type)) {
- if (!(includes & 536870912 /* EmptyObject */)) {
- includes |= 536870912 /* EmptyObject */;
+ if (!(includes & 8388608 /* IncludesEmptyObject */)) {
+ includes |= 8388608 /* IncludesEmptyObject */;
typeSet.push(type);
}
}
else {
- includes |= flags & ~939524096 /* ConstructionFlags */;
+ includes |= flags & 1835007 /* IncludesMask */;
if (flags & 3 /* AnyOrUnknown */) {
if (type === wildcardType)
- includes |= 268435456 /* Wildcard */;
+ includes |= 4194304 /* IncludesWildcard */;
}
else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) {
typeSet.push(type);
@@ -39517,8 +39897,8 @@
// Add the given types to the given type set. Order is preserved, freshness is removed from literal
// types, duplicates are removed, and nested types of the given kind are flattened into the set.
function addTypesToIntersection(typeSet, includes, types) {
- for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
- var type = types_7[_i];
+ for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
+ var type = types_8[_i];
includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
}
return includes;
@@ -39561,7 +39941,7 @@
// 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 & 1048576 /* Union */) && t.primitiveTypesOnly; });
+ var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); });
if (index < 0) {
return false;
}
@@ -39570,7 +39950,7 @@
// the unionTypes array.
while (i < types.length) {
var t = types[i];
- if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) {
+ if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) {
(unionTypes || (unionTypes = [types[index]])).push(t);
ts.orderedRemoveItemAt(types, i);
}
@@ -39599,7 +39979,7 @@
}
}
// Finally replace the first union with the result
- types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true);
+ types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */);
return true;
}
// We normalize combinations of intersection and union types based on the distributive property of the '&'
@@ -39619,7 +39999,7 @@
return neverType;
}
if (includes & 1 /* Any */) {
- return includes & 268435456 /* Wildcard */ ? wildcardType : anyType;
+ return includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType;
}
if (!strictNullChecks && includes & 98304 /* Nullable */) {
return includes & 32768 /* Undefined */ ? undefinedType : nullType;
@@ -39630,7 +40010,7 @@
includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
removeRedundantPrimitiveTypes(typeSet, includes);
}
- if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) {
+ if (includes & 8388608 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
}
if (typeSet.length === 0) {
@@ -39655,9 +40035,9 @@
var id = getTypeListId(typeSet);
var type = intersectionTypes.get(id);
if (!type) {
- var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */);
- type = createType(2097152 /* Intersection */ | propagatedFlags);
+ type = createType(2097152 /* Intersection */);
intersectionTypes.set(id, type);
+ type.objectFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */);
type.types = typeSet;
type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
type.aliasTypeArguments = aliasTypeArguments;
@@ -39712,7 +40092,7 @@
return neverType;
}
function getLiteralTypeFromProperties(type, include) {
- return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); }));
+ return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
}
function getNonEnumNumberIndexInfo(type) {
var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
@@ -39754,6 +40134,9 @@
? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
: errorType;
break;
+ case 133 /* ReadonlyKeyword */:
+ links.resolvedType = getTypeFromTypeNode(node.type);
+ break;
}
}
return links.resolvedType; // TODO: GH#18217
@@ -39856,7 +40239,10 @@
return anyType;
}
if (accessExpression && !isConstEnumObjectType(objectType)) {
- if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
+ if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
+ error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
+ }
+ else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
}
@@ -39908,7 +40294,7 @@
: accessNode;
}
function isGenericObjectType(type) {
- return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */);
+ return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 131072 /* GenericMappedType */);
}
function isGenericIndexType(type) {
return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */);
@@ -39954,12 +40340,15 @@
// that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
// construct the type Box<T[X]>.
if (isGenericMappedType(objectType)) {
- var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
- var templateMapper = combineTypeMappers(objectType.mapper, mapper);
- return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType);
+ return type.simplified = mapType(substituteIndexedMappedType(objectType, type.indexType), getSimplifiedType);
}
return type.simplified = type;
}
+ function substituteIndexedMappedType(objectType, index) {
+ var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
+ var templateMapper = combineTypeMappers(objectType.mapper, mapper);
+ return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
+ }
function getIndexedAccessType(objectType, indexType, accessNode, missingType) {
if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; }
if (objectType === wildcardType || indexType === wildcardType) {
@@ -40041,13 +40430,48 @@
function getActualTypeVariable(type) {
return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type;
}
+ /**
+ * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
+ */
+ function isIntersectionEmpty(type1, type2) {
+ return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
+ }
function getConditionalType(root, mapper) {
var checkType = instantiateType(root.checkType, mapper);
var extendsType = instantiateType(root.extendsType, mapper);
if (checkType === wildcardType || extendsType === wildcardType) {
return wildcardType;
}
- var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */);
+ var trueType = instantiateType(root.trueType, mapper);
+ var falseType = instantiateType(root.falseType, mapper);
+ var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType);
+ var result = conditionalTypes.get(instantiationId);
+ if (result) {
+ return result;
+ }
+ var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType);
+ conditionalTypes.set(instantiationId, newResult);
+ return newResult;
+ }
+ function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) {
+ // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
+ if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
+ if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
+ return trueType;
+ }
+ else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
+ return neverType;
+ }
+ }
+ else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
+ if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
+ return neverType;
+ }
+ else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
+ return falseType;
+ }
+ }
+ var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */);
var combinedMapper;
if (root.inferTypeParameters) {
var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
@@ -40057,25 +40481,25 @@
// types rules (i.e. proper contravariance) for inferences.
inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
}
- combinedMapper = combineTypeMappers(mapper, context);
+ combinedMapper = combineTypeMappers(mapper, context.mapper);
}
// Instantiate the extends type including inferences for 'infer T' type parameters
var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
// We attempt to resolve the conditional type only when the check and extends types are non-generic
- if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */)) {
+ if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */)) {
if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) {
- return instantiateType(root.trueType, mapper);
+ return trueType;
}
// Return union of trueType and falseType for 'any' since it matches anything
if (checkType.flags & 1 /* Any */) {
- return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]);
+ return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), falseType]);
}
- // Return falseType for a definitely false extends check. We check an instantations of the two
+ // Return falseType for a definitely false extends check. We check an instantiations of the two
// types with type parameters mapped to the wildcard type, the most permissive instantiations
// possible (the wildcard type is assignable to and from all types). If those are not related,
- // then no instatiations will be and we can just return the false branch type.
+ // then no instantiations will be and we can just return the false branch type.
if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) {
- return instantiateType(root.falseType, mapper);
+ return falseType;
}
// Return trueType for a definitely true extends check. We check instantiations of the two
// types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
@@ -40087,6 +40511,9 @@
}
}
// Return a deferred type for a check that is neither definitely true nor definitely false
+ return getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType);
+ }
+ function getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType) {
var erasedCheckType = getActualTypeVariable(checkType);
var result = createType(16777216 /* Conditional */);
result.root = root;
@@ -40094,15 +40521,14 @@
result.extendsType = extendsType;
result.mapper = mapper;
result.combinedMapper = combinedMapper;
+ result.trueType = trueType;
+ result.falseType = falseType;
result.aliasSymbol = root.aliasSymbol;
result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
return result;
}
- function getTrueTypeFromConditionalType(type) {
- return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
- }
- function getFalseTypeFromConditionalType(type) {
- return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
+ function getInferredTrueTypeFromConditionalType(type) {
+ return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper || type.mapper));
}
function getInferTypeParameters(node) {
var result;
@@ -40271,7 +40697,7 @@
* this function should be called in a left folding style, with left = previous result of getSpreadType
* and right = the new element to be spread.
*/
- function getSpreadType(left, right, symbol, typeFlags, objectFlags) {
+ function getSpreadType(left, right, symbol, objectFlags, readonly) {
if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
return anyType;
}
@@ -40285,10 +40711,10 @@
return left;
}
if (left.flags & 1048576 /* Union */) {
- return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); });
+ return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
}
if (right.flags & 1048576 /* Union */) {
- return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); });
+ return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
}
if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
return left;
@@ -40304,7 +40730,7 @@
var types = left.types;
var lastLeft = types[types.length - 1];
if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
- return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)]));
+ return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
}
}
return getIntersectionType([left, right]);
@@ -40328,7 +40754,7 @@
skippedPrivateMembers.set(rightProp.escapedName, true);
}
else if (isSpreadableProperty(rightProp)) {
- members.set(rightProp.escapedName, getSpreadSymbol(rightProp));
+ members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
}
}
for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
@@ -40352,12 +40778,11 @@
}
}
else {
- members.set(leftProp.escapedName, getSpreadSymbol(leftProp));
+ members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
}
}
- var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo));
- spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags;
- spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
+ var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
+ spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
return spread;
}
/** We approximate own properties as non-methods plus methods that are inside the object literal */
@@ -40365,25 +40790,21 @@
return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
!prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); });
}
- function getSpreadSymbol(prop) {
- var isReadonly = isReadonlySymbol(prop);
+ function getSpreadSymbol(prop, readonly) {
var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
- if (!isReadonly && !isSetonlyAccessor) {
+ if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
return prop;
}
var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
- var result = createSymbol(flags, prop.escapedName);
+ var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
result.declarations = prop.declarations;
result.nameType = prop.nameType;
result.syntheticOrigin = prop;
return result;
}
- function getNonReadonlyIndexSignature(index) {
- if (index && index.isReadonly) {
- return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration);
- }
- return index;
+ function getIndexInfoWithReadonly(info, readonly) {
+ return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
}
function createLiteralType(flags, value, symbol) {
var type = createType(flags);
@@ -40471,8 +40892,8 @@
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 120 /* AnyKeyword */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return anyType;
case 143 /* UnknownKeyword */:
return unknownType;
@@ -40519,23 +40940,23 @@
return getTypeFromUnionTypeNode(node);
case 174 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return getTypeFromJSDocNullableTypeNode(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return addOptionality(getTypeFromTypeNode(node.type));
case 177 /* ParenthesizedType */:
case 172 /* RestType */:
- case 287 /* JSDocNonNullableType */:
- case 283 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 288 /* JSDocTypeExpression */:
return getTypeFromTypeNode(node.type);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 297 /* JSDocTypeLiteral */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 179 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
@@ -40611,16 +41032,8 @@
* Maps forward-references to later types parameters to the empty object type.
* This is used during inference when instantiating type parameter defaults.
*/
- function createBackreferenceMapper(typeParameters, index) {
- return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; };
- }
- function isInferenceContext(mapper) {
- return !!mapper.typeParameters;
- }
- function cloneTypeMapper(mapper) {
- return mapper && isInferenceContext(mapper) ?
- createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) :
- mapper;
+ function createBackreferenceMapper(context, index) {
+ return function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? emptyObjectType : t; };
}
function combineTypeMappers(mapper1, mapper2) {
if (!mapper1)
@@ -40703,7 +41116,7 @@
}
// 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) & (2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */));
+ var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */));
result.declarations = symbol.declarations;
result.parent = symbol.parent;
result.target = symbol;
@@ -40799,7 +41212,7 @@
function getHomomorphicTypeVariable(type) {
var constraintType = getConstraintTypeFromMappedType(type);
if (constraintType.flags & 4194304 /* Index */) {
- var typeVariable = constraintType.type;
+ var typeVariable = getActualTypeVariable(constraintType.type);
if (typeVariable.flags & 262144 /* TypeParameter */) {
return typeVariable;
}
@@ -40821,30 +41234,27 @@
if (typeVariable) {
var mappedTypeVariable = instantiateType(typeVariable, mapper);
if (typeVariable !== mappedTypeVariable) {
- // If we are already in the process of creating an instantiation of this mapped type,
- // return the error type. This situation only arises if we are instantiating the mapped
- // type for an array or tuple type, as we then need to eagerly resolve the (possibly
- // circular) element type(s).
- if (type.instantiating) {
- return errorType;
- }
- type.instantiating = true;
- var result = mapType(mappedTypeVariable, function (t) {
- if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) {
+ return mapType(mappedTypeVariable, function (t) {
+ if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
var replacementMapper = createReplacementMapper(typeVariable, t, mapper);
- return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
- isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
+ return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
instantiateAnonymousType(type, replacementMapper);
}
return t;
});
- type.instantiating = false;
- return result;
}
}
return instantiateAnonymousType(type, mapper);
}
+ function getModifiedReadonlyState(state, modifiers) {
+ return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
+ }
+ function instantiateMappedArrayType(arrayType, mappedType, mapper) {
+ var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
+ return elementType === errorType ? errorType :
+ createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
+ }
function instantiateMappedTupleType(tupleType, mappedType, mapper) {
var minLength = tupleType.target.minLength;
var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) {
@@ -40854,7 +41264,9 @@
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);
+ var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
+ return ts.contains(elementTypes, errorType) ? errorType :
+ createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames);
}
function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key]));
@@ -40920,6 +41332,7 @@
// We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
// with a combination of infinite generic types that perpetually generate new type identities. We stop
// the recursion here by yielding the error type.
+ error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
return errorType;
}
instantiationDepth++;
@@ -40971,7 +41384,17 @@
return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
}
if (flags & 33554432 /* Substitution */) {
- return instantiateType(type.typeVariable, mapper);
+ var maybeVariable = instantiateType(type.typeVariable, mapper);
+ if (maybeVariable.flags & 8650752 /* TypeVariable */) {
+ return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
+ }
+ else {
+ var sub = instantiateType(type.substitute, mapper);
+ if (sub.flags & 3 /* AnyOrUnknown */ || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
+ return maybeVariable;
+ }
+ return sub;
+ }
}
return type;
}
@@ -40980,8 +41403,20 @@
type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
}
function getRestrictiveInstantiation(type) {
- return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
- type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper));
+ if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
+ return type;
+ }
+ if (type.restrictiveInstantiation) {
+ return type.restrictiveInstantiation;
+ }
+ type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
+ // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
+ // which is redundant - we'll produce new type identities, but all type params have already been mapped.
+ // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
+ // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
+ // are constrained to `unknown` and produce tons of false positives/negatives!
+ type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
+ return type.restrictiveInstantiation;
}
function instantiateIndexInfo(info, mapper) {
return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
@@ -41180,7 +41615,7 @@
var resultObj = {};
checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj);
var diagnostic = resultObj.error;
- addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
return true;
}
}
@@ -41215,7 +41650,7 @@
checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj);
if (resultObj.error) {
if (target.symbol && ts.length(target.symbol.declarations)) {
- addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
+ ts.addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
}
return true;
}
@@ -41262,13 +41697,13 @@
undefined;
if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
issuedElaboration = true;
- addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
+ ts.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))) {
var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
- addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
+ ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
}
}
}
@@ -41339,7 +41774,7 @@
// child is of the type of the expression
return { errorNode: child, innerExpression: child.expression, nameType: nameType };
case 11 /* JsxText */:
- if (child.containsOnlyWhiteSpaces) {
+ if (child.containsOnlyTriviaWhiteSpaces) {
break; // Whitespace only jsx text isn't real jsx text
}
// child is a string
@@ -41362,7 +41797,7 @@
var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
var childrenNameType = getLiteralType(childrenPropName);
var childrenTargetType = getIndexedAccessType(target, childrenNameType);
- var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyWhiteSpaces; });
+ var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
if (!ts.length(validChildren)) {
return result;
}
@@ -41450,7 +41885,7 @@
return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation);
}
// recreate a tuple from the elements, if possible
- var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true);
+ var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
if (isTupleLikeType(tupleizedType)) {
return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation);
}
@@ -41516,6 +41951,14 @@
/*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */;
}
/**
+ * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
+ */
+ function isAnySignature(s) {
+ return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
+ s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
+ isTypeAny(getReturnTypeOfSignature(s));
+ }
+ /**
* See signatureRelatedTo, compareSignaturesIdentical
*/
function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) {
@@ -41523,13 +41966,16 @@
if (source === target) {
return -1 /* True */;
}
+ if (isAnySignature(target)) {
+ return -1 /* True */;
+ }
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);
+ source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
}
var sourceCount = getParameterCount(source);
var sourceRestType = getNonArrayRestType(source);
@@ -41600,7 +42046,7 @@
if (targetTypePredicate) {
var sourceTypePredicate = getTypePredicateOfSignature(source);
if (sourceTypePredicate) {
- result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217
+ result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
}
else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
if (reportErrors) {
@@ -41619,7 +42065,7 @@
}
return result;
}
- function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) {
+ function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
if (source.kind !== target.kind) {
if (reportErrors) {
errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
@@ -41628,12 +42074,9 @@
return 0 /* False */;
}
if (source.kind === 1 /* Identifier */) {
- var targetPredicate = target;
- var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0);
- var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0);
- if (sourceIndex !== targetIndex) {
+ if (source.parameterIndex !== target.parameterIndex) {
if (reportErrors) {
- errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName);
+ errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
}
return 0 /* False */;
@@ -41834,7 +42277,7 @@
}
var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
if (relatedInfo) {
- addRelatedInfo.apply(void 0, [diag].concat(relatedInfo));
+ ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInfo));
}
if (errorOutputContainer) {
errorOutputContainer.error = diag;
@@ -42441,8 +42884,8 @@
if (source.root.isDistributive === target.root.isDistributive) {
if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
- if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
- if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
+ if (result_3 &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) {
+ if (result_3 &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) {
return result_3;
}
}
@@ -42457,6 +42900,7 @@
}
var result;
var originalErrorInfo;
+ var varianceCheckFailed = false;
var saveErrorInfo = errorInfo;
// We limit alias variance probing to only object and conditional types since their alias behavior
// is more predictable than other, interned types, which may or may not have an alias depending on
@@ -42465,11 +42909,10 @@
source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
!(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
var variances = getAliasVariances(source.aliasSymbol);
- if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) {
- return result;
+ var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances);
+ if (varianceResult !== undefined) {
+ return varianceResult;
}
- originalErrorInfo = errorInfo;
- errorInfo = saveErrorInfo;
}
if (target.flags & 262144 /* TypeParameter */) {
// A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q].
@@ -42526,9 +42969,18 @@
template.indexType === getTypeParameterFromMappedType(target)) {
return -1 /* True */;
}
+ if (!isGenericMappedType(source)) {
+ var targetConstraint = getConstraintTypeFromMappedType(target);
+ var sourceKeys_1 = getIndexType(source);
+ var hasOptionalUnionKeys = modifiers & 4 /* IncludeOptional */ && targetConstraint.flags & 1048576 /* Union */;
+ var filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, function (t) { return !!isRelatedTo(t, sourceKeys_1); }) : undefined;
// A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X.
- if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) {
- var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target));
+ // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X.
+ if (hasOptionalUnionKeys
+ ? !(filteredByApplicability.flags & 131072 /* Never */)
+ : isRelatedTo(targetConstraint, sourceKeys_1)) {
+ var indexingType = hasOptionalUnionKeys ? filteredByApplicability : getTypeParameterFromMappedType(target);
+ var indexedAccessType = getIndexedAccessType(source, indexingType);
var templateType = getTemplateTypeFromMappedType(target);
if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
return result;
@@ -42538,6 +42990,7 @@
errorInfo = saveErrorInfo;
}
}
+ }
if (source.flags & 8650752 /* TypeVariable */) {
if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
// A type S[K] is related to a type T[J] if S is related to T and K is related to J.
@@ -42581,8 +43034,8 @@
// and Y1 is related to Y2.
if (isTypeIdenticalTo(source.extendsType, target.extendsType) &&
(isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
- if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) {
- result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
+ if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) {
+ result &= isRelatedTo(source.falseType, target.falseType, reportErrors);
}
if (result) {
errorInfo = saveErrorInfo;
@@ -42631,36 +43084,19 @@
// type references (which are intended by be compared structurally). Obtain the variance
// information for the type parameters and relate the type arguments accordingly.
var variances = getVariances(source.target);
- if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) {
- return result;
- }
- // The type arguments did not relate appropriately, but it may be because we have no variance
- // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
- // arguments). It might also be the case that the target type has a 'void' type argument for
- // a covariant type parameter that is only used in return positions within the generic type
- // (in which case any type argument is permitted on the source side). In those cases we proceed
- // with a structural comparison. Otherwise, we know for certain the instantiations aren't
- // related and we can return here.
- if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) {
- // In some cases generic types that are covariant in regular type checking mode become
- // invariant in --strictFunctionTypes mode because one or more type parameters are used in
- // both co- and contravariant positions. In order to make it easier to diagnose *why* such
- // types are invariant, if any of the type parameters are invariant we reset the reported
- // errors and instead force a structural comparison (which will include elaborations that
- // reveal the reason).
- if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) {
- return 0 /* False */;
+ var varianceResult = relateVariances(source.typeArguments, target.typeArguments, variances);
+ if (varianceResult !== undefined) {
+ return varianceResult;
}
- // We remember the original error information so we can restore it in case the structural
- // comparison unexpectedly succeeds. This can happen when the structural comparison result
- // is a Ternary.Maybe for example caused by the recursion depth limiter.
- originalErrorInfo = errorInfo;
- errorInfo = saveErrorInfo;
}
- }
- else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) {
+ else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
}
+ // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
+ // and not `{} <- fresh({}) <- {[idx: string]: any}`
+ else if (relation === subtypeRelation && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
+ return 0 /* False */;
+ }
// Even if relationship doesn't hold for unions, intersections, or generic type references,
// it may hold in a structural comparison.
// In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
@@ -42682,17 +43118,57 @@
}
}
}
- if (result) {
- if (!originalErrorInfo) {
- errorInfo = saveErrorInfo;
+ if (varianceCheckFailed && result) {
+ errorInfo = originalErrorInfo || errorInfo || saveErrorInfo; // Use variance error (there is no structural one) and return false
+ }
+ else if (result) {
return result;
}
- errorInfo = originalErrorInfo;
}
}
+ return 0 /* False */;
+ function isNonGeneric(type) {
+ // If we're already in identity relationship checking, we should use `isRelatedTo`
+ // to catch the `Maybe` from an excessively deep type (which we then assume means
+ // that the type could possibly contain a generic)
+ if (relation === identityRelation) {
+ return isRelatedTo(type, getPermissiveInstantiation(type)) === -1 /* True */;
+ }
+ return isTypeIdenticalTo(type, getPermissiveInstantiation(type));
}
+ function relateVariances(sourceTypeArguments, targetTypeArguments, variances) {
+ if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors)) {
+ return result;
+ }
+ var allowStructuralFallback = (targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances)) || isNonGeneric(source) || isNonGeneric(target);
+ varianceCheckFailed = !allowStructuralFallback;
+ // The type arguments did not relate appropriately, but it may be because we have no variance
+ // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
+ // arguments). It might also be the case that the target type has a 'void' type argument for
+ // a covariant type parameter that is only used in return positions within the generic type
+ // (in which case any type argument is permitted on the source side). In those cases we proceed
+ // with a structural comparison. Otherwise, we know for certain the instantiations aren't
+ // related and we can return here.
+ if (variances !== ts.emptyArray && !allowStructuralFallback) {
+ // In some cases generic types that are covariant in regular type checking mode become
+ // invariant in --strictFunctionTypes mode because one or more type parameters are used in
+ // both co- and contravariant positions. In order to make it easier to diagnose *why* such
+ // types are invariant, if any of the type parameters are invariant we reset the reported
+ // errors and instead force a structural comparison (which will include elaborations that
+ // reveal the reason).
+ // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
+ // we can return `False` early here to skip calculating the structural error message we don't need.
+ if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) {
return 0 /* False */;
}
+ // We remember the original error information so we can restore it in case the structural
+ // comparison unexpectedly succeeds. This can happen when the structural comparison result
+ // is a Ternary.Maybe for example caused by the recursion depth limiter.
+ originalErrorInfo = errorInfo;
+ errorInfo = saveErrorInfo;
+ }
+ }
+ }
// A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
// related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
// that S and T are contra-variant whereas X and Y are co-variant.
@@ -43171,20 +43647,17 @@
return variances;
}
function getVariances(type) {
- if (!strictFunctionTypes) {
- return ts.emptyArray;
- }
- if (type === globalArrayType || type === globalReadonlyArrayType) {
- // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters)
+ // Arrays and tuples are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters)
+ if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
return ts.emptyArray;
}
return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
}
// Return true if the given type reference has a 'void' type argument for a covariant type parameter.
// See comment at call in recursiveTypeRelatedTo for when this case matters.
- function hasCovariantVoidArgument(type, variances) {
+ function hasCovariantVoidArgument(typeArguments, variances) {
for (var i = 0; i < variances.length; i++) {
- if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) {
+ if (variances[i] === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
return true;
}
}
@@ -43413,8 +43886,8 @@
}
function literalTypesWithSameBaseType(types) {
var commonBaseType;
- for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
- var t = types_8[_i];
+ for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
+ var t = types_9[_i];
var baseType = getBaseTypeOfLiteralType(t);
if (!commonBaseType) {
commonBaseType = baseType;
@@ -43447,7 +43920,7 @@
return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
}
function isArrayType(type) {
- return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType;
+ return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
}
function isReadonlyArrayType(type) {
return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
@@ -43458,8 +43931,7 @@
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<any>
- return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) ||
- !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
+ return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
}
function isEmptyArrayLiteralType(type) {
var elementType = isArrayType(type) ? type.typeArguments[0] : undefined;
@@ -43544,8 +44016,8 @@
}
function getFalsyFlagsOfTypes(types) {
var result = 0;
- for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
- var t = types_9[_i];
+ for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
+ var t = types_10[_i];
result |= getFalsyFlags(t);
}
return result;
@@ -43659,7 +44131,7 @@
var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
regularNew.flags = resolved.flags;
- regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */);
+ regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
type.regularType = regularNew;
return regularNew;
}
@@ -43738,14 +44210,14 @@
var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
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
+ result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening
return result;
}
function getWidenedType(type) {
return getWidenedTypeWithContext(type, /*context*/ undefined);
}
function getWidenedTypeWithContext(type, context) {
- if (type.flags & 402653184 /* RequiresWidening */) {
+ if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) {
if (type.flags & 98304 /* Nullable */) {
return anyType;
}
@@ -43782,7 +44254,7 @@
*/
function reportWideningErrorsInType(type) {
var errorReported = false;
- if (type.flags & 134217728 /* ContainsWideningType */) {
+ if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) {
if (type.flags & 1048576 /* Union */) {
if (ts.some(type.types, isEmptyObjectType)) {
errorReported = true;
@@ -43808,7 +44280,7 @@
for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
var p = _e[_d];
var t = getTypeOfSymbol(p);
- if (t.flags & 134217728 /* ContainsWideningType */) {
+ if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) {
if (!reportWideningErrorsInType(t)) {
error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
}
@@ -43854,7 +44326,7 @@
return;
}
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
return;
case 239 /* FunctionDeclaration */:
@@ -43881,14 +44353,14 @@
errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
}
function reportErrorsFromWidening(declaration, type) {
- if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) {
+ if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) {
// Report implicit any error within type if possible, otherwise report error on declaration
if (!reportWideningErrorsInType(type)) {
reportImplicitAny(declaration, type);
}
}
}
- function forEachMatchingParameterType(source, target, callback) {
+ function applyToParameterTypes(source, target, callback) {
var sourceCount = getParameterCount(source);
var targetCount = getParameterCount(target);
var sourceRestType = getEffectiveRestType(source);
@@ -43909,25 +44381,55 @@
callback(getRestTypeAtPosition(source, paramCount), targetRestType);
}
}
- function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) {
- var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo);
- var context = mapper;
- context.typeParameters = typeParameters;
- context.signature = signature;
- context.inferences = inferences;
- context.flags = flags;
- context.compareTypes = compareTypes || compareTypesAssignable;
+ function applyToReturnTypes(source, target, callback) {
+ var sourceTypePredicate = getTypePredicateOfSignature(source);
+ var targetTypePredicate = getTypePredicateOfSignature(target);
+ if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind &&
+ (sourceTypePredicate.kind === 0 /* This */ || sourceTypePredicate.parameterIndex === targetTypePredicate.parameterIndex)) {
+ callback(sourceTypePredicate.type, targetTypePredicate.type);
+ }
+ else {
+ callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
+ }
+ }
+ function createInferenceContext(typeParameters, signature, flags, compareTypes) {
+ return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
+ }
+ function cloneInferenceContext(context, extraFlags) {
+ if (extraFlags === void 0) { extraFlags = 0; }
+ return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
+ }
+ function cloneInferredPartOfContext(context) {
+ var inferences = ts.filter(context.inferences, hasInferenceCandidates);
+ return inferences.length ?
+ createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
+ undefined;
+ }
+ function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
+ var context = {
+ inferences: inferences,
+ signature: signature,
+ flags: flags,
+ compareTypes: compareTypes,
+ mapper: function (t) { return mapToInferredType(context, t, /*fix*/ true); },
+ nonFixingMapper: function (t) { return mapToInferredType(context, t, /*fix*/ false); },
+ };
return context;
- function mapper(t) {
+ }
+ function mapToInferredType(context, t, fix) {
+ var inferences = context.inferences;
for (var i = 0; i < inferences.length; i++) {
- if (t === inferences[i].typeParameter) {
- inferences[i].isFixed = true;
+ var inference = inferences[i];
+ if (t === inference.typeParameter) {
+ if (fix && !inference.isFixed) {
+ inference.isFixed = true;
+ inference.inferredType = undefined;
+ }
return getInferredType(context, i);
}
}
return t;
}
- }
function createInferenceInfo(typeParameter) {
return {
typeParameter: typeParameter,
@@ -43950,6 +44452,9 @@
isFixed: inference.isFixed
};
}
+ function getMapperFromContext(context) {
+ return context && context.mapper;
+ }
// Return true if the given type could possibly reference a type parameter for which
// we perform type inference (i.e. a type parameter of a generic function). We cache
// results for union and intersection types for performance reasons.
@@ -44006,31 +44511,21 @@
return type;
}
function createReverseMappedType(source, target, constraint) {
- var properties = getPropertiesOfType(source);
- if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) {
- return undefined;
- }
// If any property contains context sensitive functions that have been skipped, the source type
// is incomplete and we can't infer a meaningful input type.
- for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
- var prop = properties_3[_i];
- if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) {
+ if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || getPropertiesOfType(source).length === 0 && !getIndexInfoOfType(source, 0 /* String */)) {
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, constraint));
- }
- if (isReadonlyArrayType(source)) {
- return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint));
+ return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint), isReadonlyArrayType(source));
}
if (isTupleType(source)) {
var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); });
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);
+ return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, 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.
@@ -44051,16 +44546,16 @@
return getTypeFromInference(inference);
}
function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
- var properties, _i, properties_4, targetProp, sourceProp, targetType, sourceType;
+ var properties, _i, properties_3, targetProp, sourceProp, targetType, sourceType;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target);
- _i = 0, properties_4 = properties;
+ _i = 0, properties_3 = properties;
_a.label = 1;
case 1:
- if (!(_i < properties_4.length)) return [3 /*break*/, 6];
- targetProp = properties_4[_i];
+ if (!(_i < properties_3.length)) return [3 /*break*/, 6];
+ targetProp = properties_3[_i];
if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 5];
sourceProp = getPropertyOfType(source, targetProp.escapedName);
if (!!sourceProp) return [3 /*break*/, 3];
@@ -44104,11 +44599,11 @@
inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
emptyObjectType;
}
- function inferTypes(inferences, originalSource, originalTarget, priority) {
+ function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
if (priority === void 0) { priority = 0; }
+ if (contravariant === void 0) { contravariant = false; }
var symbolStack;
var visited;
- var contravariant = false;
var bivariant = false;
var propagationType;
var allowComplexConstraintInference = true;
@@ -44184,7 +44679,7 @@
// not contain anyFunctionType when we come back to this argument for its second round
// of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
// when constructing types from type parameters that had no inference candidates).
- if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) {
+ if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) {
return;
}
var inference = getInferenceInfoForType(target);
@@ -44193,6 +44688,7 @@
if (inference.priority === undefined || priority < inference.priority) {
inference.candidates = undefined;
inference.contraCandidates = undefined;
+ inference.topLevel = true;
inference.priority = priority;
}
if (priority === inference.priority) {
@@ -44200,14 +44696,19 @@
// We make contravariant inferences only if we are in a pure contravariant position,
// i.e. only if we have not descended into a bivariant position.
if (contravariant && !bivariant) {
- inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate);
+ if (!ts.contains(inference.contraCandidates, candidate)) {
+ inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
+ inference.inferredType = undefined;
}
- else {
- inference.candidates = ts.appendIfUnique(inference.candidates, candidate);
+ }
+ else if (!ts.contains(inference.candidates, candidate)) {
+ inference.candidates = ts.append(inference.candidates, candidate);
+ inference.inferredType = undefined;
}
}
- if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) {
+ if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
inference.topLevel = false;
+ inference.inferredType = undefined;
}
}
return;
@@ -44231,6 +44732,9 @@
}
}
}
+ else if (target.flags & 33554432 /* Substitution */) {
+ inferFromTypes(source, target.typeVariable);
+ }
if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) {
// If source and target are references to the same generic type, infer from type arguments
var sourceTypes = source.typeArguments || ts.emptyArray;
@@ -44267,42 +44771,48 @@
else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) {
inferFromTypes(source.checkType, target.checkType);
inferFromTypes(source.extendsType, target.extendsType);
- inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
- inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
+ inferFromTypes(source.trueType, target.trueType);
+ inferFromTypes(source.falseType, target.falseType);
}
- else if (target.flags & 16777216 /* Conditional */) {
- inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]));
+ else if (target.flags & 16777216 /* Conditional */ && !contravariant) {
+ inferFromTypes(source, target.trueType);
+ inferFromTypes(source, target.falseType);
}
else if (target.flags & 3145728 /* UnionOrIntersection */) {
- var targetTypes = target.types;
+ // We infer from types that are not naked type variables first so that inferences we
+ // make from nested naked type variables and given slightly higher priority by virtue
+ // of being first in the candidates array.
var typeVariableCount = 0;
- var typeVariable = void 0;
- // First infer to each type in union or intersection that isn't a type variable
- for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) {
- var t = targetTypes_3[_d];
+ for (var _d = 0, _e = target.types; _d < _e.length; _d++) {
+ var t = _e[_d];
if (getInferenceInfoForType(t)) {
- typeVariable = t;
typeVariableCount++;
}
else {
inferFromTypes(source, t);
}
}
- // Next, if target containings a single naked type variable, make a secondary inference to that type
- // variable. This gives meaningful results for union types in co-variant positions and intersection
- // types in contra-variant positions (such as callback parameters).
- if (typeVariableCount === 1) {
+ // Inferences directly to naked type variables are given lower priority as they are
+ // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
+ // we want to infer string for T, not Promise<string> | string. For intersection types
+ // we only infer to single naked type variables.
+ if (target.flags & 1048576 /* Union */ ? typeVariableCount !== 0 : typeVariableCount === 1) {
var savePriority = priority;
priority |= 1 /* NakedTypeVariable */;
- inferFromTypes(source, typeVariable);
+ for (var _f = 0, _g = target.types; _f < _g.length; _f++) {
+ var t = _g[_f];
+ if (getInferenceInfoForType(t)) {
+ inferFromTypes(source, t);
+ }
+ }
priority = savePriority;
}
}
else if (source.flags & 1048576 /* Union */) {
// Source is a union or intersection type, infer from each constituent type
var sourceTypes = source.types;
- for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) {
- var sourceType = sourceTypes_3[_e];
+ for (var _h = 0, sourceTypes_3 = sourceTypes; _h < sourceTypes_3.length; _h++) {
+ var sourceType = sourceTypes_3[_h];
inferFromTypes(sourceType, target);
}
}
@@ -44318,7 +44828,7 @@
// that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
// here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
// (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
- // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just
+ // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
// remove this `allowComplexConstraintInference` flag.
allowComplexConstraintInference = false;
return inferFromTypes(apparentSource, target);
@@ -44380,12 +44890,12 @@
}
return undefined;
}
- function inferFromMappedTypeConstraint(source, target, constraintType) {
+ function inferToMappedType(source, target, constraintType) {
if (constraintType.flags & 1048576 /* Union */) {
var result = false;
for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
var type = _a[_i];
- result = inferFromMappedTypeConstraint(source, target, type) || result;
+ result = inferToMappedType(source, target, type) || result;
}
return result;
}
@@ -44407,12 +44917,22 @@
return true;
}
if (constraintType.flags & 262144 /* TypeParameter */) {
- // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type
- // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X.
+ // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
+ // parameter. First infer from 'keyof S' to K.
var savePriority = priority;
priority |= 4 /* MappedTypeConstraint */;
inferFromTypes(getIndexType(source), constraintType);
priority = savePriority;
+ // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
+ // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
+ // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
+ // Pick<T, K>.
+ var extendedConstraint = getConstraintOfType(constraintType);
+ if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
+ return true;
+ }
+ // If no inferences can be made to K's constraint, infer from a union of the property types
+ // in the source to the template type X.
var valueTypes = ts.compact([
getIndexTypeOfType(source, 0 /* String */),
getIndexTypeOfType(source, 1 /* Number */)
@@ -44431,7 +44951,7 @@
}
if (ts.getObjectFlags(target) & 32 /* Mapped */) {
var constraintType = getConstraintTypeFromMappedType(target);
- if (inferFromMappedTypeConstraint(source, target, constraintType)) {
+ if (inferToMappedType(source, target, constraintType)) {
return;
}
}
@@ -44444,11 +44964,11 @@
}
}
function inferFromProperties(source, target) {
- if (isTupleType(source)) {
+ if (isArrayType(source) || isTupleType(source)) {
if (isTupleType(target)) {
- var sourceLength = getLengthOfTupleType(source);
+ var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0;
var targetLength = getLengthOfTupleType(target);
- var sourceRestType = getRestTypeOfTupleType(source);
+ var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source);
var targetRestType = getRestTypeOfTupleType(target);
var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
for (var i = 0; i < fixedLength; i++) {
@@ -44471,8 +44991,8 @@
}
}
var properties = getPropertiesOfObjectType(target);
- for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
- var targetProp = properties_5[_i];
+ for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) {
+ var targetProp = properties_4[_i];
var sourceProp = getPropertyOfType(source, targetProp.escapedName);
if (sourceProp) {
inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
@@ -44485,7 +45005,7 @@
var sourceLen = sourceSignatures.length;
var targetLen = targetSignatures.length;
var len = sourceLen < targetLen ? sourceLen : targetLen;
- var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */);
+ var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */);
for (var i = 0; i < len; i++) {
inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters);
}
@@ -44496,17 +45016,10 @@
var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
// Once we descend into a bivariant signature we remain bivariant for all nested inferences
bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */;
- forEachMatchingParameterType(source, target, inferFromContravariantTypes);
+ applyToParameterTypes(source, target, inferFromContravariantTypes);
bivariant = saveBivariant;
}
- var sourceTypePredicate = getTypePredicateOfSignature(source);
- var targetTypePredicate = getTypePredicateOfSignature(target);
- if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) {
- inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type);
- }
- else {
- inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
- }
+ applyToReturnTypes(source, target, inferFromTypes);
}
function inferFromIndexTypes(source, target) {
var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
@@ -44529,8 +45042,8 @@
}
}
function typeIdenticalToSomeType(type, types) {
- for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
- var t = types_10[_i];
+ for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
+ var t = types_11[_i];
if (isTypeIdenticalTo(t, type)) {
return true;
}
@@ -44623,7 +45136,7 @@
if (defaultType) {
// Instantiate the default type. Any forward reference to a type
// parameter should be instantiated to the empty object type.
- inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
}
else {
inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
@@ -44636,7 +45149,7 @@
inference.inferredType = inferredType;
var constraint = getConstraintOfTypeParameter(inference.typeParameter);
if (constraint) {
- var instantiatedConstraint = instantiateType(constraint, context);
+ var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
inference.inferredType = inferredType = instantiatedConstraint;
}
@@ -44661,17 +45174,23 @@
case "console":
return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
case "$":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
case "describe":
case "suite":
case "it":
case "test":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha;
case "process":
case "require":
case "Buffer":
case "module":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
case "Map":
case "Set":
case "Promise":
@@ -44807,9 +45326,8 @@
}
return false;
}
- function hasNarrowableDeclaredType(expr) {
- var type = getDeclaredTypeOfReference(expr);
- return !!(type && type.flags & 1048576 /* Union */);
+ function isSyntheticThisPropertyAccess(expr) {
+ return ts.isAccessExpression(expr) && expr.expression.kind === 100 /* ThisKeyword */ && !!(expr.expression.flags & 8 /* Synthesized */);
}
function findDiscriminantProperties(sourceProperties, target) {
var result;
@@ -44886,8 +45404,8 @@
}
function getTypeFactsOfTypes(types) {
var result = 0 /* None */;
- for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
- var t = types_11[_i];
+ for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
+ var t = types_12[_i];
result |= getTypeFacts(t);
}
return result;
@@ -45167,7 +45685,7 @@
if (type.flags & 1048576 /* Union */) {
var types = type.types;
var filtered = ts.filter(types, f);
- return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly);
+ return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
}
return f(type) ? type : neverType;
}
@@ -45181,8 +45699,8 @@
var types = type.types;
var mappedType;
var mappedTypes;
- for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
- var current = types_12[_i];
+ for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
+ var current = types_13[_i];
var t = mapper(current);
if (t) {
if (!mappedType) {
@@ -45264,8 +45782,8 @@
}
function isEvolvingArrayTypeList(types) {
var hasEvolvingArrayType = false;
- for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
- var t = types_13[_i];
+ for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
+ var t = types_14[_i];
if (!(t.flags & 131072 /* Never */)) {
if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
return false;
@@ -45763,6 +46281,15 @@
assumeTrue = !assumeTrue;
}
var valueType = getTypeOfExpression(value);
+ if ((type.flags & 2 /* Unknown */) && (operator === 35 /* EqualsEqualsEqualsToken */) && assumeTrue) {
+ if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
+ return valueType;
+ }
+ if (valueType.flags & 524288 /* Object */) {
+ return nonPrimitiveType;
+ }
+ return type;
+ }
if (valueType.flags & 98304 /* Nullable */) {
if (!strictNullChecks) {
return type;
@@ -45792,9 +46319,9 @@
// We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands
var target = getReferenceCandidate(typeOfExpr.expression);
if (!isMatchingReference(reference, target)) {
- // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a
- // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type.
- if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) {
+ // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the
+ // narrowed type of 'y' to its declared type.
+ if (containsMatchingReference(reference, target)) {
return declaredType;
}
return type;
@@ -45835,13 +46362,37 @@
}
}
function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
- // We only narrow if all case expressions specify values with unit types
+ // We only narrow if all case expressions specify
+ // values with unit types, except for the case where
+ // `type` is unknown. In this instance we map object
+ // types to the nonPrimitive type and narrow with that.
var switchTypes = getSwitchClauseTypes(switchStatement);
if (!switchTypes.length) {
return type;
}
var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
+ if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
+ var groundClauseTypes = void 0;
+ for (var i = 0; i < clauseTypes.length; i += 1) {
+ var t = clauseTypes[i];
+ if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
+ if (groundClauseTypes !== undefined) {
+ groundClauseTypes.push(t);
+ }
+ }
+ else if (t.flags & 524288 /* Object */) {
+ if (groundClauseTypes === undefined) {
+ groundClauseTypes = clauseTypes.slice(0, i);
+ }
+ groundClauseTypes.push(nonPrimitiveType);
+ }
+ else {
+ return type;
+ }
+ }
+ return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
+ }
var discriminantType = getUnionType(clauseTypes);
var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
@@ -45942,9 +46493,14 @@
function narrowTypeByInstanceof(type, expr, assumeTrue) {
var left = getReferenceCandidate(expr.left);
if (!isMatchingReference(reference, left)) {
- // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an
- // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type.
- if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) {
+ // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the
+ // narrowed type of 'y' to its declared type. We do this because preceding 'x.y'
+ // references might reference a different 'y' property. However, we make an exception
+ // for property accesses where x is a synthetic 'this' expression, indicating that we
+ // were called from isPropertyInitializedInConstructor. Without this exception,
+ // initializations of 'this' properties that occur before a 'this instanceof XXX'
+ // check would not be considered.
+ if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) {
return declaredType;
}
return type;
@@ -46011,7 +46567,7 @@
return type;
}
if (ts.isIdentifierTypePredicate(predicate)) {
- var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)];
+ var predicateArgument = callExpression.arguments[predicate.parameterIndex];
if (predicateArgument) {
if (isMatchingReference(reference, predicateArgument)) {
return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
@@ -46088,7 +46644,7 @@
return ts.findAncestor(node.parent, function (node) {
return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
node.kind === 245 /* ModuleBlock */ ||
- node.kind === 279 /* SourceFile */ ||
+ node.kind === 284 /* SourceFile */ ||
node.kind === 154 /* PropertyDeclaration */;
});
}
@@ -46209,7 +46765,7 @@
// 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 !== 279 /* SourceFile */) {
+ while (container.kind !== 284 /* SourceFile */) {
if (container.parent === declaration) {
if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
@@ -46315,6 +46871,7 @@
function checkNestedBlockScopedBinding(node, symbol) {
if (languageVersion >= 2 /* ES2015 */ ||
(symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
+ ts.isSourceFile(symbol.valueDeclaration) ||
symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) {
return;
}
@@ -46502,22 +47059,27 @@
if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
captureLexicalThis(node, container);
}
- var type = tryGetThisTypeAt(node, container);
- if (!type && noImplicitThis) {
+ var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
+ if (noImplicitThis) {
+ var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
+ if (type === globalThisType_1 && capturedByArrowFunction) {
+ error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
+ }
+ else if (!type) {
// With noImplicitThis, functions may not reference 'this' if it has type 'any'
- var diag = error(node, capturedByArrowFunction && container.kind === 279 /* 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);
+ var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
if (!ts.isSourceFile(container)) {
var outsideThis = tryGetThisTypeAt(container);
- if (outsideThis) {
- addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
+ if (outsideThis && outsideThis !== globalThisType_1) {
+ ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
+ }
}
}
}
return type || anyType;
}
- function tryGetThisTypeAt(node, container) {
+ function tryGetThisTypeAt(node, includeGlobalThis, container) {
+ if (includeGlobalThis === void 0) { includeGlobalThis = true; }
if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
var isInJS = ts.isInJSFile(node);
if (ts.isFunctionLike(container) &&
@@ -46562,6 +47124,16 @@
return getFlowTypeOfReference(node, type);
}
}
+ if (ts.isSourceFile(container)) {
+ // look up in the source file's locals or exports
+ if (container.commonJsModuleIndicator) {
+ var fileSymbol = getSymbolOfNode(container);
+ return fileSymbol && getTypeOfSymbol(fileSymbol);
+ }
+ else if (includeGlobalThis) {
+ return getTypeOfSymbol(globalThisSymbol);
+ }
+ }
}
function getClassNameFromPrototypeMethod(container) {
// Check if it's the RHS of a x.prototype.y = function [name]() { .... }
@@ -46617,7 +47189,7 @@
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 294 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -46631,7 +47203,7 @@
}
}
function isInConstructorArgumentInitializer(node, constructorDecl) {
- return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; });
+ return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 151 /* Parameter */ && n.parent === constructorDecl; });
}
function checkSuperExpression(node) {
var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node;
@@ -46856,7 +47428,7 @@
while (type) {
var thisType = getThisTypeFromContextualType(type);
if (thisType) {
- return instantiateType(thisType, getContextualMapper(containingLiteral));
+ return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
}
if (literal.parent.kind !== 275 /* PropertyAssignment */) {
break;
@@ -47151,7 +47723,15 @@
}
function getTypeOfPropertyOfContextualType(type, name) {
return mapType(type, function (t) {
- if (t.flags & 3670016 /* StructuredType */) {
+ if (isGenericMappedType(t)) {
+ var constraint = getConstraintTypeFromMappedType(t);
+ var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
+ var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
+ if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
+ return substituteIndexedMappedType(t, propertyNameType);
+ }
+ }
+ else if (t.flags & 3670016 /* StructuredType */) {
var prop = getPropertyOfType(t, name);
if (prop) {
return getTypeOfSymbol(prop);
@@ -47287,18 +47867,46 @@
// Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
// be "pushed" onto a node using the contextualType property.
function getApparentTypeOfContextualType(node) {
- var contextualType = getContextualType(node);
- contextualType = contextualType && mapType(contextualType, getApparentType);
- if (contextualType && contextualType.flags & 1048576 /* Union */) {
+ var contextualType = instantiateContextualType(getContextualType(node), node);
+ if (contextualType) {
+ var apparentType = mapType(contextualType, getApparentType, /*noReductions*/ true);
+ if (apparentType.flags & 1048576 /* Union */) {
if (ts.isObjectLiteralExpression(node)) {
- return discriminateContextualTypeByObjectMembers(node, contextualType);
+ return discriminateContextualTypeByObjectMembers(node, apparentType);
}
else if (ts.isJsxAttributes(node)) {
- return discriminateContextualTypeByJSXAttributes(node, contextualType);
+ return discriminateContextualTypeByJSXAttributes(node, apparentType);
+ }
+ }
+ return apparentType;
+ }
+ }
+ // If the given contextual type contains instantiable types and if a mapper representing
+ // return type inferences is available, instantiate those types using that mapper.
+ function instantiateContextualType(contextualType, node) {
+ if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) {
+ var inferenceContext = getInferenceContext(node);
+ if (inferenceContext && inferenceContext.returnMapper) {
+ return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
}
}
return contextualType;
}
+ // This function is similar to instantiateType, except that (a) it only instantiates types that
+ // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
+ // no reductions on instantiated union types.
+ function instantiateInstantiableTypes(type, mapper) {
+ if (type.flags & 63176704 /* Instantiable */) {
+ return instantiateType(type, mapper);
+ }
+ if (type.flags & 1048576 /* Union */) {
+ return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
+ }
+ if (type.flags & 2097152 /* Intersection */) {
+ return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
+ }
+ return type;
+ }
/**
* Woah! Do you really want to use this function?
*
@@ -47344,7 +47952,7 @@
return getContextualTypeForArgument(parent, node);
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- return getTypeFromTypeNode(parent.type);
+ return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type);
case 204 /* BinaryExpression */:
return getContextualTypeForBinaryOperand(node);
case 275 /* PropertyAssignment */:
@@ -47378,9 +47986,9 @@
}
return undefined;
}
- function getContextualMapper(node) {
- var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; });
- return ancestor ? ancestor.contextualMapper : identityMapper;
+ function getInferenceContext(node) {
+ var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
+ return ancestor && ancestor.inferenceContext;
}
function getContextualJsxElementAttributesType(node) {
if (ts.isJsxOpeningElement(node) && node.parent.contextualType) {
@@ -47561,8 +48169,8 @@
}
var signatureList;
var types = type.types;
- for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
- var current = types_14[_i];
+ for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
+ var current = types_15[_i];
var signature = getContextualCallSignature(current, node);
if (signature) {
if (!signatureList) {
@@ -47580,12 +48188,7 @@
}
}
// Result is union of signatures collected (return type is union of return types of this signature set)
- var result;
- if (signatureList) {
- result = cloneSignature(signatureList[0]);
- result.unionSignatures = signatureList;
- }
- return result;
+ return signatureList && createUnionSignature(signatureList[0], signatureList);
}
function checkSpreadExpression(node, checkMode) {
if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
@@ -47605,6 +48208,7 @@
var elementTypes = [];
var inDestructuringPattern = ts.isAssignmentTarget(node);
var contextualType = getApparentTypeOfContextualType(node);
+ var inConstContext = isConstContext(node);
for (var index = 0; index < elementCount; index++) {
var e = elements[index];
if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) {
@@ -47647,21 +48251,24 @@
type.pattern = node;
return type;
}
- else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) {
+ else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, inConstContext)) {
return tupleResult;
}
else if (forceTuple) {
return createTupleType(elementTypes, minLength, hasRestElement);
}
}
- return getArrayLiteralType(elementTypes, 2 /* Subtype */);
+ return createArrayType(elementTypes.length ?
+ getUnionType(elementTypes, 2 /* Subtype */) :
+ strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext);
}
- function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) {
+ function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) {
if (elementCount === void 0) { elementCount = elementTypes.length; }
+ if (readonly === void 0) { readonly = false; }
// Infer a tuple type when the contextual type is or contains a tuple-like type
- if (contextualType && forEachType(contextualType, isTupleLikeType)) {
+ if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) {
var minLength = elementCount - (hasRestElement ? 1 : 0);
- var pattern = contextualType.pattern;
+ var pattern = contextualType && 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 (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) {
@@ -47679,14 +48286,8 @@
}
}
}
- return createTupleType(elementTypes, minLength, hasRestElement);
- }
+ return createTupleType(elementTypes, minLength, hasRestElement, readonly);
}
- function getArrayLiteralType(elementTypes, unionReduction) {
- if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
- return createArrayType(elementTypes.length ?
- getUnionType(elementTypes, unionReduction) :
- strictNullChecks ? implicitNeverType : undefinedWideningType);
}
function isNumericName(name) {
switch (name.kind) {
@@ -47750,15 +48351,15 @@
}
return links.resolvedType;
}
- function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) {
+ function getObjectLiteralIndexInfo(node, offset, properties, kind) {
var propTypes = [];
for (var i = 0; i < properties.length; i++) {
- if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) {
+ if (kind === 0 /* String */ || isNumericName(node.properties[i + offset].name)) {
propTypes.push(getTypeOfSymbol(properties[i]));
}
}
var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
- return createIndexInfo(unionType, /*isReadonly*/ false);
+ return createIndexInfo(unionType, isConstContext(node));
}
function getImmediateAliasedSymbol(symbol) {
ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
@@ -47778,14 +48379,15 @@
var propertiesTable;
var propertiesArray = [];
var spread = emptyObjectType;
- var propagatedFlags = 0;
var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */);
+ var inConstContext = isConstContext(node);
+ var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
var enumTag = ts.getJSDocEnumTag(node);
var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
- var typeFlags = 0;
+ var objectFlags = freshObjectLiteralFlag;
var patternWithComputedProperties = false;
var hasComputedStringProperty = false;
var hasComputedNumberProperty = false;
@@ -47812,11 +48414,11 @@
checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
}
}
- typeFlags |= type.flags;
+ objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */;
var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
var prop = nameType ?
- createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), 2048 /* Late */) :
- createSymbol(4 /* Property */ | member.flags, member.escapedName);
+ createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 2048 /* Late */) :
+ createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
if (nameType) {
prop.nameType = nameType;
}
@@ -47854,19 +48456,18 @@
checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
}
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
propertiesArray = [];
propertiesTable = ts.createSymbolTable();
hasComputedStringProperty = false;
hasComputedNumberProperty = false;
- typeFlags = 0;
}
var type = checkExpression(memberDecl.expression);
if (!isValidSpreadType(type)) {
error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
return errorType;
}
- spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
offset = i + 1;
continue;
}
@@ -47913,17 +48514,16 @@
}
if (spread !== emptyObjectType) {
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
}
return spread;
}
return createObjectLiteralType();
function createObjectLiteralType() {
- var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined;
- var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined;
+ var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
+ var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
- result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */;
- result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag;
+ result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
if (isJSObjectLiteral) {
result.objectFlags |= 16384 /* JSLiteral */;
}
@@ -47933,7 +48533,6 @@
if (inDestructuringPattern) {
result.pattern = node;
}
- propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */;
return result;
}
}
@@ -48009,7 +48608,6 @@
var hasSpreadAnyType = false;
var typeToIntersect;
var explicitlySpecifyChildrenAttribute = false;
- var typeFlags = 0;
var objectFlags = 4096 /* JsxAttributes */;
var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
@@ -48017,7 +48615,7 @@
var member = attributeDecl.symbol;
if (ts.isJsxAttribute(attributeDecl)) {
var exprType = checkJsxAttribute(attributeDecl, checkMode);
- typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */;
+ objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */;
var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
attributeSymbol.declarations = member.declarations;
attributeSymbol.parent = member.parent;
@@ -48034,7 +48632,7 @@
else {
ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */);
if (attributesTable.size > 0) {
- spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
attributesTable = ts.createSymbolTable();
}
var exprType = checkExpressionCached(attributeDecl.expression, checkMode);
@@ -48042,7 +48640,7 @@
hasSpreadAnyType = true;
}
if (isValidSpreadType(exprType)) {
- spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
}
else {
typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
@@ -48051,7 +48649,7 @@
}
if (!hasSpreadAnyType) {
if (attributesTable.size > 0) {
- spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
}
}
// Handle children attribute
@@ -48079,7 +48677,7 @@
childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
var childPropMap = ts.createSymbolTable();
childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
- spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
}
}
if (hasSpreadAnyType) {
@@ -48097,8 +48695,7 @@
function createJsxAttributesType() {
objectFlags |= freshObjectLiteralFlag;
var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
- result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags;
- result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags;
+ result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
return result;
}
}
@@ -48109,7 +48706,7 @@
// In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
// because then type of children property will have constituent of string type.
if (child.kind === 11 /* JsxText */) {
- if (!child.containsOnlyWhiteSpaces) {
+ if (!child.containsOnlyTriviaWhiteSpaces) {
childrenTypes.push(stringType);
}
}
@@ -48180,7 +48777,7 @@
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 */);
+ var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
if (candidate) {
if (links) {
links.jsxNamespace = candidate;
@@ -48385,7 +48982,7 @@
// Mark local symbol as referenced here because it might not have been marked
// if jsx emit was not react as there wont be error being emitted
reactSym.isReferenced = 67108863 /* All */;
- // If react symbol is alias, mark it as refereced
+ // If react symbol is alias, mark it as referenced
if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) {
markAliasSymbolAsReferenced(reactSym);
}
@@ -48623,6 +49220,15 @@
if (isJSLiteralType(leftType)) {
return anyType;
}
+ if (leftType.symbol === globalThisSymbol) {
+ if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
+ error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
+ }
+ else if (noImplicitAny) {
+ error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
+ }
+ return anyType;
+ }
if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType);
}
@@ -48701,7 +49307,7 @@
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));
+ ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
}
}
function isInPropertyInitializer(node) {
@@ -48710,7 +49316,19 @@
case 154 /* PropertyDeclaration */:
return true;
case 275 /* PropertyAssignment */:
- // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`.
+ case 156 /* MethodDeclaration */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
+ case 277 /* SpreadAssignment */:
+ case 149 /* ComputedPropertyName */:
+ case 216 /* TemplateSpan */:
+ case 270 /* JsxExpression */:
+ case 267 /* JsxAttribute */:
+ case 268 /* JsxAttributes */:
+ case 269 /* JsxSpreadAttribute */:
+ case 262 /* JsxOpeningElement */:
+ case 211 /* ExpressionWithTypeArguments */:
+ case 273 /* HeritageClause */:
return false;
default:
return ts.isExpressionNode(node) ? false : "quit";
@@ -48778,7 +49396,7 @@
}
var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
if (relatedInfo) {
- addRelatedInfo(resultDiagnostic, relatedInfo);
+ ts.addRelatedInfo(resultDiagnostic, relatedInfo);
}
diagnostics.add(resultDiagnostic);
}
@@ -49177,38 +49795,34 @@
return undefined;
}
// 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) {
+ function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
- var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature;
- forEachMatchingParameterType(sourceSignature, signature, function (source, target) {
+ // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
+ // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
+ // for T but leave it possible to later infer '[any]' back to A.
+ var restType = getEffectiveRestType(contextualSignature);
+ var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
+ var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
+ applyToParameterTypes(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, source, target);
});
- if (!contextualMapper) {
- inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */);
+ if (!inferenceContext) {
+ applyToReturnTypes(contextualSignature, signature, function (source, target) {
+ inferTypes(context.inferences, source, target, 8 /* ReturnType */);
+ });
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
}
- function inferJsxTypeArguments(node, signature, excludeArgument, context) {
+ function inferJsxTypeArguments(node, signature, checkMode, context) {
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context);
+ var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
inferTypes(context.inferences, checkAttrType, paramType);
return getInferredTypes(context);
}
- function inferTypeArguments(node, signature, args, excludeArgument, context) {
- // Clear out all the inference results from the last time inferTypeArguments was called on this context
- for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) {
- var inference = _a[_i];
- // As an optimization, we don't have to clear (and later recompute) inferred types
- // for type parameters that have already been fixed on the previous call to inferTypeArguments.
- // It would be just as correct to reset all of them. But then we'd be repeating the same work
- // for the type parameters that were fixed, namely the work done by getInferredType.
- if (!inference.isFixed) {
- inference.inferredType = undefined;
- }
- }
+ function inferTypeArguments(node, signature, args, checkMode, context) {
if (ts.isJsxOpeningLikeElement(node)) {
- return inferJsxTypeArguments(node, signature, excludeArgument, context);
+ return inferJsxTypeArguments(node, signature, checkMode, context);
}
// If a contextual type is available, infer from that type to the return type of the call expression. For
// example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
@@ -49217,10 +49831,11 @@
if (node.kind !== 152 /* Decorator */) {
var contextualType = getContextualType(node);
if (contextualType) {
- // We clone the contextual mapper to avoid disturbing a resolution in progress for an
+ // We clone the inference context to avoid disturbing a resolution in progress for an
// outer call expression. Effectively we just want a snapshot of whatever has been
// inferred for any outer call expression so far.
- var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node)));
+ var outerMapper = getMapperFromContext(cloneInferenceContext(getInferenceContext(node), 1 /* NoDefault */));
+ var instantiatedType = instantiateType(contextualType, outerMapper);
// If the contextual type is a generic function type with a single call signature, we
// instantiate the type with its own type parameters and type arguments. This ensures that
// the type parameters are not erased to type any during type inference such that they can
@@ -49235,6 +49850,9 @@
var inferenceTargetType = getReturnTypeOfSignature(signature);
// Inferences made from return types have lower priority than all other inferences.
inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */);
+ // Create a type mapper for instantiating generic contextual types using the inferences made
+ // from the return type.
+ context.returnMapper = getMapperFromContext(cloneInferredPartOfContext(context));
}
}
var thisType = getThisTypeOfSignature(signature);
@@ -49249,10 +49867,7 @@
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- // For context sensitive arguments we pass the identityMapper, which is a signal to treat all
- // context sensitive function expressions as wildcards
- var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
- var argType = checkExpressionWithContextualType(arg, paramType, mapper);
+ var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
inferTypes(context.inferences, argType, paramType);
}
}
@@ -49276,7 +49891,7 @@
// and the argument are ...x forms.
return arg.kind === 215 /* SyntheticExpression */ ?
createArrayType(arg.type) :
- getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context));
+ getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
}
}
var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType;
@@ -49284,7 +49899,7 @@
var types = [];
var spreadIndex = -1;
for (var i = index; i < argCount; i++) {
- var argType = checkExpressionWithContextualType(args[i], contextualType, context);
+ var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
if (spreadIndex < 0 && isSpreadArgument(args[i])) {
spreadIndex = i - index;
}
@@ -49334,19 +49949,18 @@
* @param node a JSX opening-like element we are trying to figure its call signature
* @param signature a candidate signature we are trying whether it is a call signature
* @param relation a relationship to check parameter and argument type
- * @param excludeArgument
*/
- function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors) {
// Stateless function components can have maximum of three arguments: "props", "context", and "updater".
// However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
// can be specified by users through attributes property.
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined);
+ var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes);
}
- function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignature(node, args, signature, relation, checkMode, reportErrors) {
if (ts.isJsxOpeningLikeElement(node)) {
- return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors);
+ return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors);
}
var thisType = getThisTypeOfSignature(signature);
if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) {
@@ -49368,11 +49982,11 @@
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
- // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter),
+ var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
+ // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
// 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;
+ var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
return false;
}
@@ -49529,25 +50143,41 @@
if (argCount <= max && hasSpreadArgument) {
argCount--;
}
+ var spanArray;
var related;
+ var error = hasRestParameter || hasSpreadArgument ? 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 : ts.Diagnostics.Expected_0_arguments_but_got_1;
if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
if (paramDecl) {
related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined);
}
}
- 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;
- var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount);
- return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1;
- }
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);
}
- var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount);
- return related ? addRelatedInfo(diagnostic, related) : diagnostic;
+ if (!hasSpreadArgument && argCount < min) {
+ var diagnostic_1 = ts.createDiagnosticForNode(node, error, paramRange, argCount);
+ return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
+ }
+ if (hasRestParameter || hasSpreadArgument) {
+ spanArray = ts.createNodeArray(args);
+ if (hasSpreadArgument && argCount) {
+ var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
+ spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
+ }
+ }
+ else {
+ spanArray = ts.createNodeArray(args.slice(max));
+ }
+ spanArray.pos = ts.first(spanArray).pos;
+ spanArray.end = ts.last(spanArray).end;
+ if (spanArray.end === spanArray.pos) {
+ spanArray.end++;
+ }
+ var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
+ return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
}
function getTypeArgumentArityError(node, signatures, typeArguments) {
var argCount = typeArguments.length;
@@ -49577,7 +50207,7 @@
}
return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
}
- function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) {
+ function resolveCall(node, signatures, candidatesOutArray, checkMode, fallbackError) {
var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */;
var isDecorator = node.kind === 152 /* Decorator */;
var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
@@ -49613,7 +50243,7 @@
// For a decorator, no arguments are susceptible to contextual typing due to the fact
// decorators are applied to a declaration by the emitter, and not to an expression.
var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
- var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined;
+ var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
// The following variables are captured and modified by calls to chooseOverload.
// If overload resolution or type argument inference fails, we want to report the
// best error possible. The best error is one which says that an argument was not
@@ -49641,7 +50271,7 @@
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 = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
+ var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 191 /* 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
@@ -49667,12 +50297,7 @@
// skip the checkApplicableSignature check.
if (reportErrors) {
if (candidateForArgumentError) {
- // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...]
- // The importance of excludeArgument is to prevent us from typing function expression parameters
- // in arguments too early. If possible, we'd like to only type them once we know the correct
- // overload. However, this matters for the case where the call is correct. When the call is
- // 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);
+ checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, 0 /* Normal */, /*reportErrors*/ true);
}
else if (candidateForArgumentArityError) {
diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
@@ -49704,7 +50329,7 @@
if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
return undefined;
}
- if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false)) {
candidateForArgumentError = candidate;
return undefined;
}
@@ -49728,9 +50353,10 @@
}
else {
inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
+ typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
+ argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
}
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// 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 (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -49741,21 +50367,21 @@
else {
checkCandidate = candidate;
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
}
continue;
}
- if (excludeArgument) {
+ if (argCheckMode) {
// If one or more context sensitive arguments were excluded, we start including
// them now (and keeping do so for any subsequent candidates) and perform a second
// round of type inference and applicability checking for this particular candidate.
- excludeArgument = undefined;
+ argCheckMode = 0 /* Normal */;
if (inferenceContext) {
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// 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 (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -49763,7 +50389,7 @@
continue;
}
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
@@ -49777,20 +50403,6 @@
return undefined;
}
}
- function getExcludeArgument(args) {
- var excludeArgument;
- // We do not need to call `getEffectiveArgumentCount` here as it only
- // applies when calculating the number of arguments for a decorator.
- for (var i = 0; i < args.length; i++) {
- if (isContextSensitive(args[i])) {
- if (!excludeArgument) {
- excludeArgument = new Array(args.length);
- }
- excludeArgument[i] = true;
- }
- }
- return excludeArgument;
- }
// 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) {
@@ -49879,7 +50491,7 @@
}
function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext);
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
return createSignatureInstantiation(candidate, typeArgumentTypes);
}
function getLongestCandidateIndex(candidates, argsCount) {
@@ -49898,7 +50510,7 @@
}
return maxParamsIndex;
}
- function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveCallExpression(node, candidatesOutArray, checkMode) {
if (node.expression.kind === 98 /* SuperKeyword */) {
var superType = checkSuperExpression(node.expression);
if (isTypeAny(superType)) {
@@ -49914,7 +50526,7 @@
var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
if (baseTypeNode) {
var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
- return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, baseConstructors, candidatesOutArray, checkMode);
}
}
return resolveUntypedCall(node);
@@ -49964,12 +50576,31 @@
}
return resolveErrorCall(node);
}
+ // When a call to a generic function is an argument to an outer call to a generic function for which
+ // inference is in process, we have a choice to make. If the inner call relies on inferences made from
+ // its contextual type to its return type, deferring the inner call processing allows the best possible
+ // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
+ // the inner call, the inner call should be processed early. There's no sure way to know which choice is
+ // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
+ // If no type arguments are specified in the inner call and at least one call signature is generic and
+ // returns a function type, we choose to defer processing. This narrowly permits function composition
+ // operators to flow inferences through return types, but otherwise processes calls right away. We
+ // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
+ // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
+ // from which we never make inferences).
+ if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
+ skippedGenericFunction(node, checkMode);
+ return resolvingSignature;
+ }
// If the function is explicitly marked with `@class`, then it must be constructed.
if (callSignatures.some(function (sig) { return ts.isInJSFile(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);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
+ }
+ function isGenericFunctionReturningFunction(signature) {
+ return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
}
/**
* TS 1.0 spec: 4.12
@@ -49981,7 +50612,7 @@
return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
!numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
}
- function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveNewExpression(node, candidatesOutArray, checkMode) {
if (node.arguments && languageVersion < 1 /* ES5 */) {
var spreadIndex = getSpreadArgumentIndex(node.arguments);
if (spreadIndex >= 0) {
@@ -50029,7 +50660,7 @@
error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
return resolveErrorCall(node);
}
- return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, constructSignatures, candidatesOutArray, checkMode);
}
// 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
@@ -50037,7 +50668,7 @@
// 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, isForSignatureHelp);
+ var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode);
if (!noImplicitAny) {
if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
@@ -50059,13 +50690,12 @@
var firstBase = baseTypes[0];
if (firstBase.flags & 2097152 /* Intersection */) {
var types = firstBase.types;
- var mixinCount = ts.countWhere(types, isMixinConstructorType);
+ var mixinFlags = findMixins(types);
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 (!mixinFlags[i]) {
if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
if (intersectionMember.symbol === target) {
return true;
@@ -50075,6 +50705,7 @@
}
}
}
+ i++;
}
return false;
}
@@ -50118,7 +50749,7 @@
var diagnostic = 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, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
+ invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
}
function invocationErrorRecovery(apparentType, kind, diagnostic) {
if (!apparentType.symbol) {
@@ -50131,10 +50762,10 @@
var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
if (!sigs || !sigs.length)
return;
- 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));
+ 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, isForSignatureHelp) {
+ function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
var tagType = checkExpression(node.tag);
var apparentType = getApparentType(tagType);
if (apparentType === errorType) {
@@ -50150,7 +50781,7 @@
invocationError(node, apparentType, 0 /* Call */);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
}
/**
* Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
@@ -50175,7 +50806,7 @@
/**
* Resolves a decorator as if it were a call expression.
*/
- function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveDecorator(node, candidatesOutArray, checkMode) {
var funcType = checkExpression(node.expression);
var apparentType = getApparentType(funcType);
if (apparentType === errorType) {
@@ -50200,7 +50831,7 @@
invocationErrorRecovery(apparentType, 0 /* Call */, diag);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode, headMessage);
}
function createSignatureForJSXIntrinsic(node, result) {
var namespace = getJsxNamespaceAt(node);
@@ -50219,11 +50850,11 @@
/*hasRestparameter*/ false,
/*hasLiteralTypes*/ false);
}
- function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
var fakeSignature = createSignatureForJSXIntrinsic(node, result);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes);
+ checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
return fakeSignature;
}
var exprTypes = checkExpression(node.tagName);
@@ -50240,7 +50871,7 @@
error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
return resolveErrorCall(node);
}
- return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, signatures, candidatesOutArray, checkMode);
}
/**
* Sometimes, we have a decorator that could accept zero arguments,
@@ -50254,19 +50885,19 @@
signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
});
}
- function resolveSignature(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveSignature(node, candidatesOutArray, checkMode) {
switch (node.kind) {
case 191 /* CallExpression */:
- return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveCallExpression(node, candidatesOutArray, checkMode);
case 192 /* NewExpression */:
- return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveNewExpression(node, candidatesOutArray, checkMode);
case 193 /* TaggedTemplateExpression */:
- return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
case 152 /* Decorator */:
- return resolveDecorator(node, candidatesOutArray, isForSignatureHelp);
+ return resolveDecorator(node, candidatesOutArray, checkMode);
case 262 /* JsxOpeningElement */:
case 261 /* JsxSelfClosingElement */:
- return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp);
+ return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
}
throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
}
@@ -50277,8 +50908,7 @@
* 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, isForSignatureHelp) {
- if (isForSignatureHelp === void 0) { isForSignatureHelp = false; }
+ function getResolvedSignature(node, candidatesOutArray, checkMode) {
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,
@@ -50289,11 +50919,15 @@
return cached;
}
links.resolvedSignature = resolvingSignature;
- var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp);
+ var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
+ // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
+ // resolution should be deferred.
+ if (result !== resolvingSignature) {
// 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.
links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ }
return result;
}
/**
@@ -50369,10 +51003,15 @@
* @param node The call/new expression to be checked.
* @returns On success, the expression's signature's return type. On failure, anyType.
*/
- function checkCallExpression(node) {
+ function checkCallExpression(node, checkMode) {
if (!checkGrammarTypeArguments(node, node.typeArguments))
checkGrammarArguments(node.arguments);
- var signature = getResolvedSignature(node);
+ var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
+ if (signature === resolvingSignature) {
+ // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
+ // returns a function type. We defer checking and return nonInferrableType.
+ return nonInferrableType;
+ }
if (node.expression.kind === 98 /* SuperKeyword */) {
return voidType;
}
@@ -50472,7 +51111,7 @@
var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
anonymousSymbol.type = defaultContainingObject;
- synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0) : defaultContainingObject;
+ synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
}
else {
synthType.syntheticType = type;
@@ -50519,9 +51158,37 @@
function checkAssertion(node) {
return checkAssertionWorker(node, node.type, node.expression);
}
+ function isValidConstAssertionArgument(node) {
+ switch (node.kind) {
+ case 10 /* StringLiteral */:
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 8 /* NumericLiteral */:
+ case 9 /* BigIntLiteral */:
+ case 102 /* TrueKeyword */:
+ case 87 /* FalseKeyword */:
+ case 187 /* ArrayLiteralExpression */:
+ case 188 /* ObjectLiteralExpression */:
+ return true;
+ case 195 /* ParenthesizedExpression */:
+ return isValidConstAssertionArgument(node.expression);
+ case 202 /* PrefixUnaryExpression */:
+ var op = node.operator;
+ var arg = node.operand;
+ return op === 39 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
+ op === 38 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
+ }
+ return false;
+ }
function checkAssertionWorker(errNode, type, expression, checkMode) {
- var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode)));
+ var exprType = checkExpression(expression, checkMode);
+ if (ts.isConstTypeReference(type)) {
+ if (!isValidConstAssertionArgument(expression)) {
+ error(expression, ts.Diagnostics.A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal);
+ }
+ return getRegularTypeOfLiteralType(exprType);
+ }
checkSourceElement(type);
+ exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
var targetType = getTypeFromTypeNode(type);
if (produceDiagnostics && targetType !== errorType) {
var widenedType = getWidenedType(exprType);
@@ -50560,7 +51227,7 @@
}
}
function checkImportMetaProperty(node) {
- if (languageVersion < 6 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) {
+ if (languageVersion < 7 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) {
error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options);
}
var file = ts.getSourceFileOfNode(node);
@@ -50588,7 +51255,7 @@
if (isTupleType(restType)) {
var associatedNames = restType.target.associatedNames;
var index = pos - paramCount;
- return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index;
+ return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
}
return restParameter.escapedName;
}
@@ -50601,33 +51268,37 @@
return getTypeOfParameter(signature.parameters[pos]);
}
if (signature.hasRestParameter) {
+ // We want to return the value undefined for an out of bounds parameter position,
+ // so we need to check bounds here before calling getIndexedAccessType (which
+ // otherwise would return the type 'undefined').
var restType = getTypeOfSymbol(signature.parameters[paramCount]);
- if (isTupleType(restType)) {
- if (pos - paramCount < getLengthOfTupleType(restType)) {
- return restType.typeArguments[pos - paramCount];
- }
- return getRestTypeOfTupleType(restType);
+ var index = pos - paramCount;
+ if (!isTupleType(restType) || restType.target.hasRestElement || index < (restType.typeArguments || ts.emptyArray).length) {
+ return getIndexedAccessType(restType, getLiteralType(index));
}
- return getIndexTypeOfType(restType, 1 /* Number */);
}
return undefined;
}
function getRestTypeAtPosition(source, pos) {
var paramCount = getParameterCount(source);
var restType = getEffectiveRestType(source);
- if (restType && pos === paramCount - 1) {
+ var nonRestCount = paramCount - (restType ? 1 : 0);
+ if (restType && pos === nonRestCount) {
return restType;
}
- var start = restType ? Math.min(pos, paramCount - 1) : pos;
var types = [];
var names = [];
- for (var i = start; i < paramCount; i++) {
+ for (var i = pos; i < nonRestCount; i++) {
types.push(getTypeAtPosition(source, i));
names.push(getParameterNameAtPosition(source, i));
}
+ if (restType) {
+ types.push(getIndexedAccessType(restType, numberType));
+ names.push(getParameterNameAtPosition(source, nonRestCount));
+ }
var minArgumentCount = getMinArgumentCount(source);
- var minLength = minArgumentCount < start ? 0 : minArgumentCount - start;
- return createTupleType(types, minLength, !!restType, names);
+ var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos;
+ return createTupleType(types, minLength, !!restType, /*readonly*/ false, names);
}
function getParameterCount(signature) {
var length = signature.parameters.length;
@@ -50675,16 +51346,27 @@
function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
}
- function inferFromAnnotatedParameters(signature, context, mapper) {
+ function inferFromAnnotatedParameters(signature, context, inferenceContext) {
var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
for (var i = 0; i < len; i++) {
var declaration = signature.parameters[i].valueDeclaration;
if (declaration.type) {
var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
if (typeNode) {
- inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
+ inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
+ }
}
}
+ var restType = getEffectiveRestType(context);
+ if (restType && restType.flags & 262144 /* TypeParameter */) {
+ // The contextual signature has a generic rest parameter. We first instantiate the contextual
+ // signature (without fixing type parameters) and assign types to contextually typed parameters.
+ var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
+ assignContextualParameterTypes(signature, instantiatedContext);
+ // We then infer from a tuple type representing the parameters that correspond to the contextual
+ // rest parameter.
+ var restPos = getParameterCount(context) - 1;
+ inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
}
}
function assignContextualParameterTypes(signature, context) {
@@ -50786,7 +51468,7 @@
var functionFlags = ts.getFunctionFlags(func);
var type;
if (func.body.kind !== 218 /* Block */) {
- type = checkExpressionCached(func.body, checkMode);
+ type = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -50964,7 +51646,7 @@
ts.forEachReturnStatement(func.body, function (returnStatement) {
var expr = returnStatement.expression;
if (expr) {
- var type = checkExpressionCached(expr, checkMode);
+ var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51057,7 +51739,7 @@
ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
checkNodeDeferred(node);
// The identityMapper object is used to indicate that function expressions are wildcards
- if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) {
+ if (checkMode && checkMode & 4 /* 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);
@@ -51067,7 +51749,7 @@
var returnType = getReturnTypeFromBody(node, checkMode);
var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
- returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */;
+ returnOnlyType.objectFlags |= 524288 /* NonInferrableType */;
return links_1.contextFreeType = returnOnlyType;
}
return anyFunctionType;
@@ -51093,12 +51775,12 @@
if (contextualSignature) {
var signature = getSignaturesOfType(type, 0 /* Call */)[0];
if (isContextSensitive(node)) {
- var contextualMapper = getContextualMapper(node);
- if (checkMode === 2 /* Inferential */) {
- inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper);
+ var inferenceContext = getInferenceContext(node);
+ if (checkMode && checkMode & 2 /* Inferential */) {
+ inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
}
- var instantiatedContextualSignature = contextualMapper === identityMapper ?
- contextualSignature : instantiateSignature(contextualSignature, contextualMapper);
+ var instantiatedContextualSignature = inferenceContext ?
+ instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
assignContextualParameterTypes(signature, instantiatedContextualSignature);
}
if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
@@ -51364,13 +52046,13 @@
// Return true if type might be of the given kind. A union or intersection type might be of a given
// kind if at least one constituent type is of the given kind.
function maybeTypeOfKind(type, kind) {
- if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) {
+ if (type.flags & kind & ~131072 /* GenericMappedType */ || kind & 131072 /* GenericMappedType */ && isGenericMappedType(type)) {
return true;
}
if (type.flags & 3145728 /* UnionOrIntersection */) {
var types = type.types;
- for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
- var t = types_15[_i];
+ for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
+ var t = types_16[_i];
if (maybeTypeOfKind(t, kind)) {
return true;
}
@@ -51449,8 +52131,8 @@
if (strictNullChecks && properties.length === 0) {
return checkNonNullType(sourceType, node);
}
- for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) {
- var p = properties_6[_i];
+ for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
+ var p = properties_5[_i];
checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis);
}
return sourceType;
@@ -51474,7 +52156,7 @@
return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
}
else if (property.kind === 277 /* SpreadAssignment */) {
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(property, 4 /* Rest */);
}
var nonRestNames = [];
@@ -51969,7 +52651,7 @@
// Async generator functions prior to ESNext require the __await, __asyncDelegator,
// and __asyncValues helpers
if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ &&
- languageVersion < 6 /* ESNext */) {
+ languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */);
}
// Generator functions prior to ES2015 require the __values helper
@@ -52016,23 +52698,26 @@
}
return node;
}
- function checkExpressionWithContextualType(node, contextualType, contextualMapper) {
+ function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
var context = getContextNode(node);
var saveContextualType = context.contextualType;
- var saveContextualMapper = context.contextualMapper;
+ var saveInferenceContext = context.inferenceContext;
context.contextualType = contextualType;
- context.contextualMapper = contextualMapper;
- var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ :
- contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */;
- var result = checkExpression(node, checkMode);
+ context.inferenceContext = inferenceContext;
+ var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
+ // We strip literal freshness when an appropriate contextual type is present such that contextually typed
+ // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
+ // here would be to not mark contextually typed literals as fresh in the first place.
+ var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
+ getRegularTypeOfLiteralType(type) : type;
context.contextualType = saveContextualType;
- context.contextualMapper = saveContextualMapper;
+ context.inferenceContext = saveInferenceContext;
return result;
}
function checkExpressionCached(node, checkMode) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- if (checkMode) {
+ if (checkMode && checkMode !== 0 /* Normal */) {
return checkExpression(node, checkMode);
}
// When computing a type that we're going to cache, we need to ignore any ongoing control flow
@@ -52095,13 +52780,17 @@
}
return false;
}
- function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
- if (arguments.length === 2) {
- contextualType = getContextualType(node);
+ function isConstContext(node) {
+ var parent = node.parent;
+ return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
+ (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
+ (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
}
+ function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
var type = checkExpression(node, checkMode, forceTuple);
- return isTypeAssertion(node) ? type :
- getWidenedLiteralLikeTypeForContextualType(type, contextualType);
+ return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
+ isTypeAssertion(node) ? type :
+ getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
}
function checkPropertyAssignment(node, checkMode) {
// Do not use hasDynamicName here, because that returns false for well known symbols.
@@ -52125,20 +52814,129 @@
return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
}
function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
+ if (checkMode & 8 /* SkipGenericFunctions */) {
+ skippedGenericFunction(node, checkMode);
+ return anyFunctionType;
+ }
var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType));
if (contextualSignature && !contextualSignature.typeParameters) {
- return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node)));
+ var context = getInferenceContext(node);
+ // We have an expression that is an argument of a generic function for which we are performing
+ // type argument inference. The expression is of a function type with a single generic call
+ // signature and a contextual function type with a single non-generic call signature. Now check
+ // if the outer function returns a function type with a single non-generic call signature and
+ // if some of the outer function type parameters have no inferences so far. If so, we can
+ // potentially add inferred type parameters to the outer function return type.
+ var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature));
+ if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
+ // Instantiate the signature with its own type parameters as type arguments, possibly
+ // renaming the type parameters to ensure they have unique names.
+ var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
+ // Infer from the parameters of the instantiated signature to the parameters of the
+ // contextual signature starting with an empty set of inference candidates.
+ var inferences_2 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
+ applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
+ inferTypes(inferences_2, source, target, /*priority*/ 0, /*contravariant*/ true);
+ });
+ if (ts.some(inferences_2, hasInferenceCandidates)) {
+ // We have inference candidates, indicating that one or more type parameters are referenced
+ // in the parameter types of the contextual signature. Now also infer from the return type.
+ applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
+ inferTypes(inferences_2, source, target);
+ });
+ // If the type parameters for which we produced candidates do not have any inferences yet,
+ // we adopt the new inference candidates and add the type parameters of the expression type
+ // to the set of inferred type parameters for the outer function return type.
+ if (!hasOverlappingInferences(context.inferences, inferences_2)) {
+ mergeInferences(context.inferences, inferences_2);
+ context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
+ return getOrCreateTypeFromSignature(instantiatedSignature);
+ }
+ }
+ }
+ return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
}
}
}
}
return type;
}
+ function skippedGenericFunction(node, checkMode) {
+ if (checkMode & 2 /* Inferential */) {
+ // We have skipped a generic function during inferential typing. Obtain the inference context and
+ // indicate this has occurred such that we know a second pass of inference is be needed.
+ var context = getInferenceContext(node);
+ context.flags |= 4 /* SkippedGenericFunction */;
+ }
+ }
+ function hasInferenceCandidates(info) {
+ return !!(info.candidates || info.contraCandidates);
+ }
+ function hasOverlappingInferences(a, b) {
+ for (var i = 0; i < a.length; i++) {
+ if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ function mergeInferences(target, source) {
+ for (var i = 0; i < target.length; i++) {
+ if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
+ target[i] = source[i];
+ }
+ }
+ }
+ function getUniqueTypeParameters(context, typeParameters) {
+ var result = [];
+ var oldTypeParameters;
+ var newTypeParameters;
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var tp = typeParameters_2[_i];
+ var name = tp.symbol.escapedName;
+ if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
+ var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
+ var symbol = createSymbol(262144 /* TypeParameter */, newName);
+ var newTypeParameter = createTypeParameter(symbol);
+ newTypeParameter.target = tp;
+ oldTypeParameters = ts.append(oldTypeParameters, tp);
+ newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
+ result.push(newTypeParameter);
+ }
+ else {
+ result.push(tp);
+ }
+ }
+ if (newTypeParameters) {
+ var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
+ for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
+ var tp = newTypeParameters_1[_a];
+ tp.mapper = mapper;
+ }
+ }
+ return result;
+ }
+ function hasTypeParameterByName(typeParameters, name) {
+ return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
+ }
+ function getUniqueTypeParameterName(typeParameters, baseName) {
+ var len = baseName.length;
+ while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
+ len--;
+ var s = baseName.slice(0, len);
+ for (var index = 1; true; index++) {
+ var augmentedName = (s + index);
+ if (!hasTypeParameterByName(typeParameters, augmentedName)) {
+ return augmentedName;
+ }
+ }
+ }
/**
* Returns the type of an expression. Unlike checkExpression, this function is simply concerned
* with computing the type and may not fully check all contained sub-expressions for errors.
@@ -52156,7 +52954,7 @@
return getReturnTypeOfSignature(signature);
}
}
- else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) {
+ else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
return getTypeFromTypeNode(expr.type);
}
// Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions
@@ -52178,27 +52976,22 @@
}
var saveContextualType = node.contextualType;
node.contextualType = anyType;
- var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */);
+ var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
node.contextualType = saveContextualType;
return type;
}
- // 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
- // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function
- // object, it serves as an indicator that all contained function and arrow expressions should be considered to
- // have the wildcard function type; this form of type check is used during overload resolution to exclude
- // contextually typed function and arrow expressions in the initial phase.
function checkExpression(node, checkMode, forceTuple) {
- var type;
- if (node.kind === 148 /* QualifiedName */) {
- type = checkQualifiedName(node);
- }
- else {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
- type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
- }
+ var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
if (isConstEnumObjectType(type)) {
+ checkConstEnumAccess(node, type);
+ }
+ currentNode = saveCurrentNode;
+ return type;
+ }
+ function checkConstEnumAccess(node, type) {
// enum object type for const enums are only permitted in:
// - 'left' in property access
// - 'object' in indexed access
@@ -52210,8 +53003,13 @@
if (!ok) {
error(node, ts.Diagnostics.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);
}
+ if (compilerOptions.isolatedModules) {
+ ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
+ var constEnumDeclaration = type.symbol.valueDeclaration;
+ if (constEnumDeclaration.flags & 4194304 /* Ambient */) {
+ error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
+ }
}
- return type;
}
function checkParenthesizedExpression(node, checkMode) {
var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
@@ -52253,6 +53051,8 @@
return checkObjectLiteral(node, checkMode);
case 189 /* PropertyAccessExpression */:
return checkPropertyAccessExpression(node);
+ case 148 /* QualifiedName */:
+ return checkQualifiedName(node);
case 190 /* ElementAccessExpression */:
return checkIndexedAccess(node);
case 191 /* CallExpression */:
@@ -52261,7 +53061,7 @@
}
/* falls through */
case 192 /* NewExpression */:
- return checkCallExpression(node);
+ return checkCallExpression(node, checkMode);
case 193 /* TaggedTemplateExpression */:
return checkTaggedTemplateExpression(node);
case 195 /* ParenthesizedExpression */:
@@ -52326,9 +53126,8 @@
checkSourceElement(node.constraint);
checkSourceElement(node.default);
var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
- if (!hasNonCircularBaseConstraint(typeParameter)) {
- error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter));
- }
+ // Resolve base constraint to reveal circularity errors
+ getBaseConstraintOfType(typeParameter);
if (!hasNonCircularTypeParameterDefault(typeParameter)) {
error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
}
@@ -52370,7 +53169,7 @@
}
// 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) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) {
+ if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) {
error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
}
}
@@ -52381,7 +53180,8 @@
error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
return;
}
- var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent));
+ var signature = getSignatureFromDeclaration(parent);
+ var typePredicate = getTypePredicateOfSignature(signature);
if (!typePredicate) {
return;
}
@@ -52392,12 +53192,12 @@
}
else {
if (typePredicate.parameterIndex >= 0) {
- if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) {
+ if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) {
error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
}
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]), node.type,
+ checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type,
/*headMessage*/ undefined, leadingError);
}
}
@@ -52464,7 +53264,7 @@
var functionFlags = ts.getFunctionFlags(node);
if (!(functionFlags & 4 /* Invalid */)) {
// Async generators prior to ESNext require the __await and __asyncGenerator helpers
- if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) {
+ if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */);
}
// Async functions prior to ES2017 require the __awaiter helper
@@ -52521,7 +53321,7 @@
checkAsyncFunctionReturnType(node, returnTypeNode);
}
}
- if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) {
+ if (node.kind !== 162 /* IndexSignature */ && node.kind !== 294 /* JSDocFunctionType */) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -53200,7 +54000,7 @@
for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) {
var signature = signatures_6[_a];
if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
- error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation);
+ ts.addRelatedInfo(error(signature.declaration, ts.Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), ts.createDiagnosticForNode(bodyDeclaration, ts.Diagnostics.The_implementation_signature_is_declared_here));
break;
}
}
@@ -53277,8 +54077,8 @@
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
// A jsdoc typedef and callback are, by definition, type aliases
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return 2 /* ExportType */;
case 244 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
@@ -53287,7 +54087,7 @@
case 240 /* ClassDeclaration */:
case 243 /* EnumDeclaration */:
return 2 /* ExportType */ | 1 /* ExportValue */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
case 254 /* ExportAssignment */:
// Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
@@ -53652,8 +54452,8 @@
}
function getEntityNameForDecoratorMetadataFromTypeList(types) {
var commonEntityName;
- for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
- var typeNode = types_16[_i];
+ for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
+ var typeNode = types_17[_i];
while (typeNode.kind === 177 /* ParenthesizedType */) {
typeNode = typeNode.type; // Skip parens if need be
}
@@ -53928,7 +54728,7 @@
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
case 246 /* CaseBlock */:
@@ -54021,8 +54821,8 @@
return;
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];
+ for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
+ var typeParameter = typeParameters_3[_i];
if (!isTypeParameterUnused(typeParameter))
continue;
var name = ts.idText(typeParameter.name);
@@ -54275,7 +55075,7 @@
}
// 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 === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
+ if (parent.kind === 284 /* 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));
}
@@ -54290,7 +55090,7 @@
}
// 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 === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
+ if (parent.kind === 284 /* 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));
}
@@ -54347,7 +55147,7 @@
(container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) ||
container.kind === 245 /* ModuleBlock */ ||
container.kind === 244 /* ModuleDeclaration */ ||
- container.kind === 279 /* SourceFile */);
+ container.kind === 284 /* 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
@@ -54447,7 +55247,7 @@
}
}
if (node.kind === 186 /* BindingElement */) {
- if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) {
+ if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 4 /* Rest */);
}
// check computed properties inside property names of binding elements
@@ -54458,7 +55258,7 @@
var parent = node.parent.parent;
var parentType = getTypeForBindingElementParent(parent);
var name = node.propertyName || node.name;
- if (!ts.isBindingPattern(name) && parentType) {
+ if (parentType && !ts.isBindingPattern(name)) {
var exprType = getLiteralTypeFromPropertyName(name);
if (isTypeUsableAsPropertyName(exprType)) {
var nameText = getPropertyNameFromType(exprType);
@@ -54645,7 +55445,7 @@
checkGrammarForInOrForOfStatement(node);
if (node.awaitModifier) {
var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
- if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) {
+ if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 7 /* ESNext */) {
// for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */);
}
@@ -55090,7 +55890,7 @@
// If the function has a return type, but promisedType is
// undefined, an error will be reported in checkAsyncFunctionReturnType
// so we don't need to report one here.
- checkTypeAssignableTo(awaitedType, promisedType, node);
+ checkTypeAssignableToAndOptionallyElaborate(awaitedType, promisedType, node, node.expression);
}
}
else {
@@ -55690,8 +56490,8 @@
for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
var base = baseTypes_2[_i];
var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
- for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) {
- var prop = properties_7[_a];
+ for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
+ var prop = properties_6[_a];
var existing = seen.get(prop.escapedName);
if (!existing) {
seen.set(prop.escapedName, { prop: prop, containingType: base });
@@ -55961,10 +56761,6 @@
checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
checkExportsOnMergedDeclarations(node);
computeEnumMemberValues(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);
- }
// Spec 2014 - Section 9.3:
// It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
// and when an enum type has multiple declarations, only one declaration is permitted to omit a value
@@ -55975,9 +56771,10 @@
var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
if (node === firstDeclaration) {
if (enumSymbol.declarations.length > 1) {
+ var enumIsConst_1 = ts.isEnumConst(node);
// check that const is placed\omitted on all enum declarations
ts.forEach(enumSymbol.declarations, function (decl) {
- if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) {
+ if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
}
});
@@ -56058,8 +56855,8 @@
var symbol = getSymbolOfNode(node);
// The following checks only apply on a non-ambient instantiated module declaration.
if (symbol.flags & 512 /* ValueModule */
- && symbol.declarations.length > 1
&& !inAmbientContext
+ && symbol.declarations.length > 1
&& isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
if (firstNonAmbientClassOrFunc) {
@@ -56200,7 +56997,7 @@
return false;
}
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule) {
error(moduleName, node.kind === 255 /* ExportDeclaration */ ?
ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
@@ -56331,7 +57128,7 @@
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ &&
!node.moduleSpecifier && node.flags & 4194304 /* Ambient */;
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
}
}
@@ -56348,7 +57145,7 @@
}
}
function checkGrammarModuleElementContext(node, errorMessage) {
- var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
+ var isInAppropriateContext = node.parent.kind === 284 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
if (!isInAppropriateContext) {
grammarErrorOnFirstToken(node, errorMessage);
}
@@ -56377,7 +57174,7 @@
// If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
return;
}
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
if (node.isExportEquals) {
error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
@@ -56470,9 +57267,14 @@
!!declaration.body;
}
function checkSourceElement(node) {
- if (!node) {
- return;
+ if (node) {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
+ checkSourceElementWorker(node);
+ currentNode = saveCurrentNode;
+ }
}
+ function checkSourceElementWorker(node) {
if (ts.isInJSFile(node)) {
ts.forEach(node.jsDoc, function (_a) {
var tags = _a.tags;
@@ -56542,32 +57344,32 @@
return checkInferType(node);
case 183 /* ImportType */:
return checkImportType(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return checkJSDocAugmentsTag(node);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return checkJSDocTypeAliasTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return checkJSDocTemplateTag(node);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return checkJSDocTypeTag(node);
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
return checkJSDocParameterTag(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
checkJSDocFunctionType(node);
// falls through
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
- case 292 /* JSDocTypeLiteral */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
+ case 297 /* JSDocTypeLiteral */:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
checkJSDocVariadicType(node);
return;
- case 283 /* JSDocTypeExpression */:
+ case 288 /* JSDocTypeExpression */:
return checkSourceElement(node.type);
case 180 /* IndexedAccessType */:
return checkIndexedAccessType(node);
@@ -56721,10 +57523,13 @@
}
function checkDeferredNodes(context) {
var links = getNodeLinks(context);
- if (!links.deferredNodes) {
- return;
+ if (links.deferredNodes) {
+ links.deferredNodes.forEach(checkDeferredNode);
}
- links.deferredNodes.forEach(function (node) {
+ }
+ function checkDeferredNode(node) {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
switch (node.kind) {
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
@@ -56746,7 +57551,7 @@
checkJsxElementDeferred(node);
break;
}
- });
+ currentNode = saveCurrentNode;
}
function checkSourceFile(node) {
ts.performance.mark("beforeCheck");
@@ -56821,7 +57626,7 @@
throwIfNonDiagnosticsProducing();
if (sourceFile) {
// Some global diagnostics are deferred until they are needed and
- // may not be reported in the firt call to getGlobalDiagnostics.
+ // may not be reported in the first call to getGlobalDiagnostics.
// We should catch these changes and report them.
var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
@@ -56872,7 +57677,7 @@
copySymbols(location.locals, meaning);
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
// falls through
@@ -57091,10 +57896,10 @@
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 299 /* JSDocParameterTag */) {
+ if (entityName.parent.kind === 304 /* JSDocParameterTag */) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) {
+ if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 308 /* JSDocTemplateTag */) {
ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true.
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -57136,7 +57941,7 @@
return undefined;
}
function getSymbolAtLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
}
var parent = node.parent;
@@ -57478,7 +58283,7 @@
}
var parentSymbol_1 = getParentOfSymbol(symbol);
if (parentSymbol_1) {
- if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) {
+ if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 284 /* 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.
@@ -57505,7 +58310,7 @@
return undefined;
}
function isSymbolOfDeclarationWithCollidingName(symbol) {
- if (symbol.flags & 418 /* BlockScoped */) {
+ if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
var links = getSymbolLinks(symbol);
if (links.isDeclarationWithCollidingName === undefined) {
var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
@@ -57593,7 +58398,7 @@
}
function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
- if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
+ if (node === undefined || node.parent.kind !== 284 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
// parent is not source file or it is not reference to internal module
return false;
}
@@ -58022,7 +58827,7 @@
break;
}
}
- if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
+ if (current.valueDeclaration && current.valueDeclaration.kind === 284 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
return false;
}
// check that at least one declaration of top level symbol originates from type declaration file
@@ -58055,7 +58860,7 @@
if (!moduleSymbol) {
return undefined;
}
- return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */);
+ return ts.getDeclarationOfKind(moduleSymbol, 284 /* SourceFile */);
}
function initializeTypeChecker() {
// Bind all source files and propagate errors
@@ -58133,7 +58938,7 @@
// autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
}
- globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1);
+ globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
if (augmentations) {
@@ -58169,8 +58974,8 @@
else {
// Otherwise issue top-level error since the files appear very identical in terms of what they contain
var list = ts.arrayFrom(conflictingSymbols.keys()).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)));
+ diagnostics.add(ts.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(ts.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;
@@ -58287,7 +59092,7 @@
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
}
else if (flags & 128 /* Abstract */) {
@@ -58310,7 +59115,7 @@
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
}
else if (node.kind === 151 /* Parameter */) {
@@ -58355,7 +59160,7 @@
flags |= 1 /* Export */;
break;
case 80 /* DefaultKeyword */:
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
}
@@ -58478,7 +59283,7 @@
case 151 /* Parameter */:
return false;
default:
- if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return false;
}
switch (node.kind) {
@@ -58566,10 +59371,10 @@
var nonSimpleParameters = getNonSimpleParameters(node.parameters);
if (ts.length(nonSimpleParameters)) {
ts.forEach(nonSimpleParameters, function (parameter) {
- addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
+ ts.addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
});
var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); });
- addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
+ ts.addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
return true;
}
}
@@ -59006,6 +59811,11 @@
return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
}
}
+ else if (node.operator === 133 /* ReadonlyKeyword */) {
+ if (node.type.kind !== 169 /* ArrayType */ && node.type.kind !== 170 /* TupleType */) {
+ return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(139 /* SymbolKeyword */));
+ }
+ }
}
function checkGrammarForInvalidDynamicName(node, message) {
if (isNonBindableDynamicName(node)) {
@@ -59396,7 +60206,7 @@
// 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 === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
var links_2 = getNodeLinks(node.parent);
// Check if the containing block ever report this error
if (!links_2.hasReportedStatementInAmbientContext) {
@@ -59436,7 +60246,7 @@
var literalType = ts.isLiteralTypeNode(node.parent) ||
ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
if (!literalType) {
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) {
return true;
}
@@ -59601,10 +60411,11 @@
return createLiteralFromNode(value);
}
ts.createLiteral = createLiteral;
- function createNumericLiteral(value) {
+ function createNumericLiteral(value, numericLiteralFlags) {
+ if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
var node = createSynthesizedNode(8 /* NumericLiteral */);
node.text = value;
- node.numericLiteralFlags = 0;
+ node.numericLiteralFlags = numericLiteralFlags;
return node;
}
ts.createNumericLiteral = createNumericLiteral;
@@ -61449,14 +62260,14 @@
// JSDoc
/* @internal */
function createJSDocTypeExpression(type) {
- var node = createSynthesizedNode(283 /* JSDocTypeExpression */);
+ var node = createSynthesizedNode(288 /* JSDocTypeExpression */);
node.type = type;
return node;
}
ts.createJSDocTypeExpression = createJSDocTypeExpression;
/* @internal */
function createJSDocTypeTag(typeExpression, comment) {
- var tag = createJSDocTag(302 /* JSDocTypeTag */, "type");
+ var tag = createJSDocTag(307 /* JSDocTypeTag */, "type");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61464,7 +62275,7 @@
ts.createJSDocTypeTag = createJSDocTypeTag;
/* @internal */
function createJSDocReturnTag(typeExpression, comment) {
- var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns");
+ var tag = createJSDocTag(305 /* JSDocReturnTag */, "returns");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61472,7 +62283,7 @@
ts.createJSDocReturnTag = createJSDocReturnTag;
/* @internal */
function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
- var tag = createJSDocTag(299 /* JSDocParameterTag */, "param");
+ var tag = createJSDocTag(304 /* JSDocParameterTag */, "param");
tag.typeExpression = typeExpression;
tag.name = name;
tag.isBracketed = isBracketed;
@@ -61482,7 +62293,7 @@
ts.createJSDocParamTag = createJSDocParamTag;
/* @internal */
function createJSDocComment(comment, tags) {
- var node = createSynthesizedNode(291 /* JSDocComment */);
+ var node = createSynthesizedNode(296 /* JSDocComment */);
node.comment = comment;
node.tags = tags;
return node;
@@ -61563,6 +62374,28 @@
return node;
}
ts.createJsxFragment = createJsxFragment;
+ function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
+ var node = createSynthesizedNode(11 /* JsxText */);
+ node.text = text;
+ node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
+ return node;
+ }
+ ts.createJsxText = createJsxText;
+ function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
+ return node.text !== text
+ || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
+ ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
+ : node;
+ }
+ ts.updateJsxText = updateJsxText;
+ function createJsxOpeningFragment() {
+ return createSynthesizedNode(265 /* JsxOpeningFragment */);
+ }
+ ts.createJsxOpeningFragment = createJsxOpeningFragment;
+ function createJsxJsxClosingFragment() {
+ return createSynthesizedNode(266 /* JsxClosingFragment */);
+ }
+ ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment;
function updateJsxFragment(node, openingFragment, children, closingFragment) {
return node.openingFragment !== openingFragment
|| node.children !== children
@@ -61741,7 +62574,7 @@
(typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
(libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
(hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
- var updated = createSynthesizedNode(279 /* SourceFile */);
+ var updated = createSynthesizedNode(284 /* SourceFile */);
updated.flags |= node.flags;
updated.statements = createNodeArray(statements);
updated.endOfFileToken = node.endOfFileToken;
@@ -61825,7 +62658,7 @@
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(307 /* NotEmittedStatement */);
+ var node = createSynthesizedNode(312 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
@@ -61837,7 +62670,7 @@
*/
/* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(316 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -61849,7 +62682,7 @@
*/
/* @internal */
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(310 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(315 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -61864,7 +62697,7 @@
* @param location The location for the expression. Defaults to the positions from "original" if provided.
*/
function createPartiallyEmittedExpression(expression, original) {
- var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */);
+ var node = createSynthesizedNode(313 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -61880,7 +62713,7 @@
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
function flattenCommaElements(node) {
if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
- if (node.kind === 309 /* CommaListExpression */) {
+ if (node.kind === 314 /* CommaListExpression */) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
@@ -61890,7 +62723,7 @@
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(309 /* CommaListExpression */);
+ var node = createSynthesizedNode(314 /* CommaListExpression */);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -61903,33 +62736,197 @@
ts.updateCommaList = updateCommaList;
function createBundle(sourceFiles, prepends) {
if (prepends === void 0) { prepends = ts.emptyArray; }
- var node = ts.createNode(280 /* Bundle */);
+ var node = ts.createNode(285 /* Bundle */);
node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, map) {
- var node = ts.createNode(281 /* UnparsedSource */);
+ var allUnscopedEmitHelpers;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
+ ts.valuesHelper,
+ ts.readHelper,
+ ts.spreadHelper,
+ ts.restHelper,
+ ts.decorateHelper,
+ ts.metadataHelper,
+ ts.paramHelper,
+ ts.awaiterHelper,
+ ts.assignHelper,
+ ts.awaitHelper,
+ ts.asyncGeneratorHelper,
+ ts.asyncDelegator,
+ ts.asyncValues,
+ ts.extendsHelper,
+ ts.templateObjectHelper,
+ ts.generatorHelper,
+ ts.importStarHelper,
+ ts.importDefaultHelper
+ ], function (helper) { return helper.name; }));
+ }
+ function createUnparsedSource() {
+ var node = ts.createNode(286 /* UnparsedSource */);
+ node.prologues = ts.emptyArray;
+ node.referencedFiles = ts.emptyArray;
+ node.libReferenceDirectives = ts.emptyArray;
+ node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
+ return node;
+ }
+ function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
+ var node = createUnparsedSource();
+ var stripInternal;
+ var bundleFileInfo;
if (!ts.isString(textOrInputFiles)) {
ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
- node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath;
+ node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
Object.defineProperties(node, {
text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
});
+ if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
+ node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
+ ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
+ stripInternal = mapTextOrStripInternal;
+ bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
+ if (node.oldFileOfCurrentEmit) {
+ parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo));
+ return node;
+ }
+ }
}
else {
+ node.fileName = "";
node.text = textOrInputFiles;
node.sourceMapPath = mapPathOrType;
- node.sourceMapText = map;
+ node.sourceMapText = mapTextOrStripInternal;
}
+ ts.Debug.assert(!node.oldFileOfCurrentEmit);
+ parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
return node;
}
ts.createUnparsedSourceFile = createUnparsedSourceFile;
- function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapText) {
- var node = ts.createNode(282 /* InputFiles */);
+ function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
+ var prologues;
+ var helpers;
+ var referencedFiles;
+ var typeReferenceDirectives;
+ var libReferenceDirectives;
+ var texts;
+ for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "prologue" /* Prologue */:
+ (prologues || (prologues = [])).push(createUnparsedNode(section, node));
+ break;
+ case "emitHelpers" /* EmitHelpers */:
+ (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ node.hasNoDefaultLib = true;
+ break;
+ case "reference" /* Reference */:
+ (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "type" /* Type */:
+ (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
+ break;
+ case "lib" /* Lib */:
+ (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "prepend" /* Prepend */:
+ var prependNode = createUnparsedNode(section, node);
+ var prependTexts = void 0;
+ for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
+ var text = _c[_b];
+ if (!stripInternal || text.kind !== "internal" /* Internal */) {
+ (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
+ }
+ }
+ prependNode.texts = prependTexts || ts.emptyArray;
+ (texts || (texts = [])).push(prependNode);
+ break;
+ case "internal" /* Internal */:
+ if (stripInternal)
+ break;
+ // falls through
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.prologues = prologues || ts.emptyArray;
+ node.helpers = helpers;
+ node.referencedFiles = referencedFiles || ts.emptyArray;
+ node.typeReferenceDirectives = typeReferenceDirectives;
+ node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
+ node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
+ }
+ function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
+ ts.Debug.assert(!!node.oldFileOfCurrentEmit);
+ var texts;
+ var syntheticReferences;
+ for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "internal" /* Internal */:
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
+ break;
+ // Ignore
+ case "prologue" /* Prologue */:
+ case "emitHelpers" /* EmitHelpers */:
+ case "prepend" /* Prepend */:
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.texts = texts || ts.emptyArray;
+ node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
+ node.syntheticReferences = syntheticReferences;
+ return node;
+ }
+ function mapBundleFileSectionKindToSyntaxKind(kind) {
+ switch (kind) {
+ case "prologue" /* Prologue */: return 279 /* UnparsedPrologue */;
+ case "prepend" /* Prepend */: return 280 /* UnparsedPrepend */;
+ case "internal" /* Internal */: return 282 /* UnparsedInternalText */;
+ case "text" /* Text */: return 281 /* UnparsedText */;
+ case "emitHelpers" /* EmitHelpers */:
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
+ default:
+ return ts.Debug.assertNever(kind);
+ }
+ }
+ function createUnparsedNode(section, parent) {
+ var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ return node;
+ }
+ function createUnparsedSyntheticReference(section, parent) {
+ var node = ts.createNode(283 /* UnparsedSyntheticReference */, section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ node.section = section;
+ return node;
+ }
+ function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
+ var node = ts.createNode(287 /* InputFiles */);
if (!ts.isString(javascriptTextOrReadFileText)) {
var cache_1 = ts.createMap();
var textGetter_1 = function (path) {
@@ -61946,15 +62943,25 @@
var result = textGetter_1(path);
return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
};
+ var buildInfo_1;
+ var getAndCacheBuildInfo_1 = function (getText) {
+ if (buildInfo_1 === undefined) {
+ var result = getText();
+ buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
+ }
+ return buildInfo_1 || undefined;
+ };
node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath;
node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath;
+ node.buildInfoPath = declarationMapTextOrBuildInfoPath;
Object.defineProperties(node, {
javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
- declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } } // TODO:: if there is inline sourceMap in dtsFile, use that
+ declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
+ buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
});
}
else {
@@ -61963,7 +62970,12 @@
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
node.declarationText = declarationTextOrJavascriptPath;
node.declarationMapPath = declarationMapPath;
- node.declarationMapText = declarationMapText;
+ node.declarationMapText = declarationMapTextOrBuildInfoPath;
+ node.javascriptPath = javascriptPath;
+ node.declarationPath = declarationPath,
+ node.buildInfoPath = buildInfoPath;
+ node.buildInfo = buildInfo;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
}
return node;
}
@@ -62101,10 +63113,10 @@
// 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 === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return node.emitNode = { annotatedNodes: [node] };
}
- var sourceFile = ts.getSourceFileOfNode(node);
+ var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
}
node.emitNode = {};
@@ -62402,7 +63414,7 @@
ts.nullTransformationContext = {
enableEmitNotification: ts.noop,
enableSubstitution: ts.noop,
- endLexicalEnvironment: function () { return undefined; },
+ endLexicalEnvironment: ts.returnUndefined,
getCompilerOptions: ts.notImplemented,
getEmitHost: ts.notImplemented,
getEmitResolver: ts.notImplemented,
@@ -62547,38 +63559,38 @@
return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
}
ts.getHelperName = getHelperName;
- var valuesHelper = {
+ ts.valuesHelper = {
name: "typescript:values",
scoped: false,
text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };"
};
function createValuesHelper(context, expression, location) {
- context.requestEmitHelper(valuesHelper);
+ context.requestEmitHelper(ts.valuesHelper);
return ts.setTextRange(ts.createCall(getHelperName("__values"),
/*typeArguments*/ undefined, [expression]), location);
}
ts.createValuesHelper = createValuesHelper;
- var readHelper = {
+ ts.readHelper = {
name: "typescript:read",
scoped: false,
text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };"
};
function createReadHelper(context, iteratorRecord, count, location) {
- context.requestEmitHelper(readHelper);
+ context.requestEmitHelper(ts.readHelper);
return ts.setTextRange(ts.createCall(getHelperName("__read"),
/*typeArguments*/ undefined, count !== undefined
? [iteratorRecord, ts.createLiteral(count)]
: [iteratorRecord]), location);
}
ts.createReadHelper = createReadHelper;
- var spreadHelper = {
+ ts.spreadHelper = {
name: "typescript:spread",
scoped: false,
text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
};
function createSpreadHelper(context, argumentList, location) {
- context.requestEmitHelper(readHelper);
- context.requestEmitHelper(spreadHelper);
+ context.requestEmitHelper(ts.readHelper);
+ context.requestEmitHelper(ts.spreadHelper);
return ts.setTextRange(ts.createCall(getHelperName("__spread"),
/*typeArguments*/ undefined, argumentList), location);
}
@@ -62749,7 +63761,7 @@
function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) {
var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
if (property === firstAccessor) {
- var properties_8 = [];
+ var properties_7 = [];
if (getAccessor) {
var getterFunction = ts.createFunctionExpression(getAccessor.modifiers,
/*asteriskToken*/ undefined,
@@ -62760,7 +63772,7 @@
ts.setTextRange(getterFunction, getAccessor);
ts.setOriginalNode(getterFunction, getAccessor);
var getter = ts.createPropertyAssignment("get", getterFunction);
- properties_8.push(getter);
+ properties_7.push(getter);
}
if (setAccessor) {
var setterFunction = ts.createFunctionExpression(setAccessor.modifiers,
@@ -62772,15 +63784,15 @@
ts.setTextRange(setterFunction, setAccessor);
ts.setOriginalNode(setterFunction, setAccessor);
var setter = ts.createPropertyAssignment("set", setterFunction);
- properties_8.push(setter);
+ properties_7.push(setter);
}
- properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
- properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
+ properties_7.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
+ properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"),
/*typeArguments*/ undefined, [
receiver,
createExpressionForPropertyName(property.name),
- ts.createObjectLiteral(properties_8, multiLine)
+ ts.createObjectLiteral(properties_7, multiLine)
]),
/*location*/ firstAccessor);
return ts.aggregateTransformFlags(expression);
@@ -63424,7 +64436,7 @@
case 190 /* ElementAccessExpression */:
case 189 /* PropertyAccessExpression */:
case 213 /* NonNullExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -63440,7 +64452,7 @@
ts.parenthesizeConciseBody = parenthesizeConciseBody;
function isCommaSequence(node) {
return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
- node.kind === 309 /* CommaListExpression */;
+ node.kind === 314 /* CommaListExpression */;
}
ts.isCommaSequence = isCommaSequence;
var OuterExpressionKinds;
@@ -63459,7 +64471,7 @@
case 212 /* AsExpression */:
case 213 /* NonNullExpression */:
return (kinds & 2 /* Assertions */) !== 0;
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
}
return false;
@@ -63496,7 +64508,7 @@
case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
- case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 313 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
/**
@@ -64288,12 +65300,12 @@
case 278 /* EnumMember */:
return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
// No need to visit nodes with no children.
@@ -64349,7 +65361,7 @@
case 220 /* EmptyStatement */:
case 210 /* OmittedExpression */:
case 236 /* DebuggerStatement */:
- case 307 /* NotEmittedStatement */:
+ case 312 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
@@ -64726,14 +65738,14 @@
result = reduceNode(node.initializer, cbNode, result);
break;
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
result = reduceNodes(node.statements, cbNodes, result);
break;
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -64747,8 +65759,8 @@
return statements;
}
return ts.isNodeArray(statements)
- ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements)
- : ts.addStatementsAfterPrologue(statements, declarations);
+ ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements)
+ : ts.insertStatementsAfterStandardPrologue(statements, declarations);
}
ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
/**
@@ -65014,7 +66026,7 @@
}
exit();
}
- function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) {
+ function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
var _a;
ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
@@ -65024,6 +66036,14 @@
var nameIndexToNewNameIndexMap;
var mappingIterator = decodeMappings(map.mappings);
for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) {
+ if (end && (raw.generatedLine > end.line ||
+ (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
+ break;
+ }
+ if (start && (raw.generatedLine < start.line ||
+ (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
+ continue;
+ }
// Then reencode all the updated mappings into the overall map
var newSourceIndex = void 0;
var newSourceLine = void 0;
@@ -65052,8 +66072,10 @@
}
}
}
- var newGeneratedLine = raw.generatedLine + generatedLine;
- var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter;
+ var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
+ var newGeneratedLine = rawGeneratedLine + generatedLine;
+ var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
+ var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
}
exit();
@@ -65536,7 +66558,7 @@
function chainBundle(transformSourceFile) {
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
+ return node.kind === 284 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
}
function transformBundle(node) {
return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
@@ -66012,8 +67034,8 @@
if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
if (flattenContext.level >= 1 /* ObjectRest */
- && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */))
- && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */))
+ && !(element.transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */))
+ && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */))
&& !ts.isComputedPropertyName(propertyName)) {
bindingElements = ts.append(bindingElements, element);
}
@@ -66079,7 +67101,7 @@
if (flattenContext.level >= 1 /* ObjectRest */) {
// If an array pattern contains an ObjectRest, we must cache the result so that we
// can perform the ObjectRest destructuring in a different declaration
- if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (element.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
if (flattenContext.hoistTempVariables) {
flattenContext.context.hoistVariableDeclaration(temp);
@@ -66197,7 +67219,7 @@
function makeAssignmentElement(name) {
return name;
}
- var restHelper = {
+ ts.restHelper = {
name: "typescript:rest",
scoped: false,
text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
@@ -66206,7 +67228,7 @@
* `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
*/
function createRestCall(context, value, elements, computedTempVariables, location) {
- context.requestEmitHelper(restHelper);
+ context.requestEmitHelper(ts.restHelper);
var propertyNames = [];
var computedTempVariableOffset = 0;
for (var i = 0; i < elements.length - 1; i++) {
@@ -66307,14 +67329,14 @@
var pendingExpressions;
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* 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 === 282 /* InputFiles */) {
+ if (prepend.kind === 287 /* InputFiles */) {
return ts.createUnparsedSourceFile(prepend, "js");
}
return prepend;
@@ -66363,7 +67385,7 @@
*/
function onBeforeVisitNode(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 245 /* ModuleBlock */:
case 218 /* Block */:
@@ -66407,14 +67429,9 @@
* @param node The node to visit.
*/
function visitorWorker(node) {
- if (node.transformFlags & 1 /* TypeScript */) {
- // This node is explicitly marked as TypeScript, so we should transform the node.
+ if (node.transformFlags & 1 /* ContainsTypeScript */) {
return visitTypeScript(node);
}
- else if (node.transformFlags & 2 /* ContainsTypeScript */) {
- // This node contains TypeScript, so we should visit its children.
- return ts.visitEachChild(node, visitor, context);
- }
return node;
}
/**
@@ -66448,7 +67465,7 @@
// As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
// We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
// and will trigger debug failures when debug verbosity is turned up
- if (node.transformFlags & 2 /* ContainsTypeScript */) {
+ if (node.transformFlags & 1 /* ContainsTypeScript */) {
// This node contains TypeScript, so we should visit its children.
return ts.visitEachChild(node, visitor, context);
}
@@ -66490,15 +67507,9 @@
// do not emit ES6 imports and exports since they are illegal inside a namespace
return undefined;
}
- else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
- // This node is explicitly marked as TypeScript, or is exported at the namespace
- // level, so we should transform the node.
+ else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
return visitTypeScript(node);
}
- else if (node.transformFlags & 2 /* ContainsTypeScript */) {
- // This node contains TypeScript, so we should visit its children.
- return ts.visitEachChild(node, visitor, context);
- }
return node;
}
/**
@@ -66549,7 +67560,7 @@
* @param node The node to visit.
*/
function visitTypeScript(node) {
- if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) {
+ if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) {
// TypeScript ambient declarations are elided, but some comments may be preserved.
// See the implementation of `getLeadingComments` in comments.ts for more details.
return ts.createNotEmittedStatement(node);
@@ -66616,7 +67627,7 @@
// See the implementation of `getLeadingComments` in comments.ts for more details.
return ts.createNotEmittedStatement(node);
case 240 /* ClassDeclaration */:
- // This is a class declaration with TypeScript syntax extensions.
+ // This may be a class declaration with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
// - decorators
@@ -66627,7 +67638,7 @@
// - method overload signatures
return visitClassDeclaration(node);
case 209 /* ClassExpression */:
- // This is a class expression with TypeScript syntax extensions.
+ // This may be a class expression with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
// - decorators
@@ -66638,7 +67649,7 @@
// - method overload signatures
return visitClassExpression(node);
case 273 /* HeritageClause */:
- // This is a heritage clause with TypeScript syntax extensions.
+ // This may be a heritage clause with TypeScript syntax extensions.
//
// TypeScript heritage clause extensions include:
// - `implements` clause
@@ -66666,7 +67677,7 @@
// TypeScript arrow functions can have modifiers and type annotations.
return visitArrowFunction(node);
case 151 /* Parameter */:
- // This is a parameter declaration with TypeScript syntax extensions.
+ // This may be a parameter declaration with TypeScript syntax extensions.
//
// TypeScript parameter declaration syntax extensions include:
// - decorators
@@ -66707,7 +67718,8 @@
// TypeScript namespace or external module import.
return visitImportEqualsDeclaration(node);
default:
- return ts.Debug.failBadSyntaxKind(node);
+ // node contains some other TypeScript syntax
+ return ts.visitEachChild(node, visitor, context);
}
}
function visitSourceFile(node) {
@@ -66756,18 +67768,19 @@
facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
return facts;
}
- /**
- * Transforms a class declaration with TypeScript syntax into compatible ES6.
- *
- * This function will only be called when one of the following conditions are met:
- * - The class has decorators.
- * - The class has property declarations with initializers.
- * - The class contains a constructor that contains parameters with accessibility modifiers.
- * - The class is an export in a TypeScript namespace.
- *
- * @param node The node to transform.
- */
+ function hasTypeScriptClassSyntax(node) {
+ return !!(node.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */);
+ }
+ function isClassLikeDeclarationWithTypeScriptSyntax(node) {
+ return ts.some(node.decorators)
+ || ts.some(node.typeParameters)
+ || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
+ || ts.some(node.members, hasTypeScriptClassSyntax);
+ }
function visitClassDeclaration(node) {
+ if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) {
+ return ts.visitEachChild(node, visitor, context);
+ }
var savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
@@ -66820,7 +67833,7 @@
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
var iife = ts.createImmediatelyInvokedArrowFunction(statements);
ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
var varStatement = ts.createVariableStatement(
@@ -66997,16 +68010,10 @@
ts.setCommentRange(statement, node);
return statement;
}
- /**
- * Transforms a class expression with TypeScript syntax into compatible ES6.
- *
- * This function will only be called when one of the following conditions are met:
- * - The class has property declarations with initializers.
- * - The class contains a constructor that contains parameters with accessibility modifiers.
- *
- * @param node The node to transform.
- */
function visitClassExpression(node) {
+ if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
+ return ts.visitEachChild(node, visitor, context);
+ }
var savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
@@ -67070,7 +68077,7 @@
var constructor = ts.getFirstConstructorWithBody(node);
var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty);
var hasParameterPropertyAssignments = constructor &&
- constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ &&
+ constructor.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */ &&
ts.forEach(constructor.parameters, isParameterWithPropertyAssignment);
// If the class does not contain nodes that require a synthesized constructor,
// accept the current constructor if it exists.
@@ -67269,8 +68276,8 @@
* @param receiver The receiver on which each property should be assigned.
*/
function addInitializedPropertyStatements(statements, properties, receiver) {
- for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
- var property = properties_9[_i];
+ for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
+ var property = properties_8[_i];
var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver));
ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
ts.setCommentRange(statement, property);
@@ -67286,8 +68293,8 @@
*/
function generateInitializedPropertyExpressions(properties, receiver) {
var expressions = [];
- for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) {
- var property = properties_10[_i];
+ for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
+ var property = properties_9[_i];
var expression = transformInitializedProperty(property, receiver);
ts.startOnNewLine(expression);
ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
@@ -67361,11 +68368,14 @@
var decorators;
if (node) {
var parameters = node.parameters;
- for (var i = 0; i < parameters.length; i++) {
- var parameter = parameters[i];
+ var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
+ var firstParameterOffset = firstParameterIsThis ? 1 : 0;
+ var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
+ for (var i = 0; i < numParameters; i++) {
+ var parameter = parameters[i + firstParameterOffset];
if (decorators || parameter.decorators) {
if (!decorators) {
- decorators = new Array(parameters.length);
+ decorators = new Array(numParameters);
}
decorators[i] = parameter.decorators;
}
@@ -67865,8 +68875,12 @@
return serializeTypeList(node.types);
case 175 /* ConditionalType */:
return serializeTypeList([node.trueType, node.falseType]);
- case 167 /* TypeQuery */:
case 179 /* TypeOperator */:
+ if (node.operator === 133 /* ReadonlyKeyword */) {
+ return serializeTypeNode(node.type);
+ }
+ break;
+ case 167 /* TypeQuery */:
case 180 /* IndexedAccessType */:
case 181 /* MappedType */:
case 168 /* TypeLiteral */:
@@ -67884,8 +68898,8 @@
// Note when updating logic here also update getEntityNameForDecoratorMetadata
// so that aliases can be marked as referenced
var serializedUnion;
- for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
- var typeNode = types_17[_i];
+ for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
+ var typeNode = types_18[_i];
while (typeNode.kind === 177 /* ParenthesizedType */) {
typeNode = typeNode.type; // Skip parens if need be
}
@@ -68027,7 +69041,7 @@
* available.
*/
function getGlobalBigIntNameWithFallback() {
- return languageVersion < 6 /* ESNext */
+ return languageVersion < 7 /* ESNext */
? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object"))
: ts.createIdentifier("BigInt");
}
@@ -68111,12 +69125,12 @@
* @param node The HeritageClause to transform.
*/
function visitHeritageClause(node) {
- if (node.token === 86 /* ExtendsKeyword */) {
- var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1);
- return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node);
- }
+ if (node.token === 109 /* ImplementsKeyword */) {
+ // implements clauses are elided
return undefined;
}
+ return ts.visitEachChild(node, visitor, context);
+ }
/**
* Transforms an ExpressionWithTypeArguments with TypeScript syntax.
*
@@ -68151,16 +69165,6 @@
}
return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context));
}
- /**
- * Visits a method declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is an overload
- * - The node is marked as abstract, public, private, protected, or readonly
- * - The node has a computed property name
- *
- * @param node The method node.
- */
function visitMethodDeclaration(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return undefined;
@@ -68187,15 +69191,6 @@
function shouldEmitAccessorDeclaration(node) {
return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));
}
- /**
- * Visits a get accessor declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked as abstract, public, private, or protected
- * - The node has a computed property name
- *
- * @param node The get accessor node.
- */
function visitGetAccessor(node) {
if (!shouldEmitAccessorDeclaration(node)) {
return undefined;
@@ -68211,15 +69206,6 @@
}
return updated;
}
- /**
- * Visits a set accessor declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked as abstract, public, private, or protected
- * - The node has a computed property name
- *
- * @param node The set accessor node.
- */
function visitSetAccessor(node) {
if (!shouldEmitAccessorDeclaration(node)) {
return undefined;
@@ -68234,16 +69220,6 @@
}
return updated;
}
- /**
- * Visits a function declaration.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is an overload
- * - The node is exported from a TypeScript namespace
- * - The node has decorators
- *
- * @param node The function node.
- */
function visitFunctionDeclaration(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return ts.createNotEmittedStatement(node);
@@ -68259,14 +69235,6 @@
}
return updated;
}
- /**
- * Visits a function expression node.
- *
- * This function will be called when one of the following conditions are met:
- * - The node has type annotations
- *
- * @param node The function expression node.
- */
function visitFunctionExpression(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return ts.createOmittedExpression();
@@ -68276,51 +69244,31 @@
/*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
return updated;
}
- /**
- * @remarks
- * This function will be called when one of the following conditions are met:
- * - The node has type annotations
- */
function visitArrowFunction(node) {
var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier),
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
/*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
return updated;
}
- /**
- * Visits a parameter declaration node.
- *
- * This function will be called when one of the following conditions are met:
- * - The node has an accessibility modifier.
- * - The node has a questionToken.
- * - The node's kind is ThisKeyword.
- *
- * @param node The parameter declaration node.
- */
function visitParameter(node) {
if (ts.parameterIsThisKeyword(node)) {
return undefined;
}
- var parameter = ts.createParameter(
+ var updated = ts.updateParameter(node,
/*decorators*/ undefined,
/*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName),
/*questionToken*/ undefined,
/*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
+ if (updated !== node) {
// While we emit the source map for the node after skipping decorators and modifiers,
// we need to emit the comments for the original range.
- ts.setOriginalNode(parameter, node);
- ts.setTextRange(parameter, ts.moveRangePastModifiers(node));
- ts.setCommentRange(parameter, node);
- ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node));
- ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */);
- return parameter;
+ ts.setCommentRange(updated, node);
+ ts.setTextRange(updated, ts.moveRangePastModifiers(node));
+ ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
+ ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
+ }
+ return updated;
}
- /**
- * Visits a variable statement in a namespace.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is exported from a TypeScript namespace.
- */
function visitVariableStatement(node) {
if (isExportOfNamespace(node)) {
var variables = ts.getInitializedVariables(node.declarationList);
@@ -68349,12 +69297,6 @@
return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName),
/*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
}
- /**
- * Visits a parenthesized expression that contains either a type assertion or an `as`
- * expression.
- *
- * @param node The parenthesized expression node.
- */
function visitParenthesizedExpression(node) {
var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */);
if (ts.isAssertionExpression(innerExpression)) {
@@ -68491,7 +69433,7 @@
var statements = [];
startLexicalEnvironment();
var members = ts.map(node.members, transformEnumMember);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
ts.addRange(statements, members);
currentNamespaceContainerName = savedCurrentNamespaceLocalName;
return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members),
@@ -68590,7 +69532,7 @@
// 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))
- ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
+ ], currentLexicalScope.kind === 284 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
ts.setOriginalNode(statement, node);
recordEmittedDeclarationInScope(node);
if (isFirstEmittedDeclarationInScope(node)) {
@@ -68738,7 +69680,7 @@
var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
currentNamespaceContainerName = savedCurrentNamespaceContainerName;
currentNamespace = savedCurrentNamespace;
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
@@ -69155,7 +70097,7 @@
// 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 !== 279 /* SourceFile */) {
+ if (container && container.kind !== 284 /* SourceFile */) {
var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) ||
(applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */);
if (substitute) {
@@ -69206,39 +70148,39 @@
argumentsArray.push(descriptor);
}
}
- context.requestEmitHelper(decorateHelper);
+ context.requestEmitHelper(ts.decorateHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"),
/*typeArguments*/ undefined, argumentsArray), location);
}
- var decorateHelper = {
+ ts.decorateHelper = {
name: "typescript:decorate",
scoped: false,
priority: 2,
text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
};
function createMetadataHelper(context, metadataKey, metadataValue) {
- context.requestEmitHelper(metadataHelper);
+ context.requestEmitHelper(ts.metadataHelper);
return ts.createCall(ts.getHelperName("__metadata"),
/*typeArguments*/ undefined, [
ts.createLiteral(metadataKey),
metadataValue
]);
}
- var metadataHelper = {
+ ts.metadataHelper = {
name: "typescript:metadata",
scoped: false,
priority: 3,
text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
};
function createParamHelper(context, expression, parameterOffset, location) {
- context.requestEmitHelper(paramHelper);
+ context.requestEmitHelper(ts.paramHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__param"),
/*typeArguments*/ undefined, [
ts.createLiteral(parameterOffset),
expression
]), location);
}
- var paramHelper = {
+ ts.paramHelper = {
name: "typescript:param",
scoped: false,
priority: 4,
@@ -69293,7 +70235,7 @@
return visited;
}
function visitor(node) {
- if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) {
+ if ((node.transformFlags & 32 /* ContainsES2017 */) === 0) {
return node;
}
switch (node.kind) {
@@ -69563,22 +70505,26 @@
}
var savedCapturedSuperProperties = capturedSuperProperties;
var savedHasSuperElementAccess = hasSuperElementAccess;
+ if (!isArrowFunction) {
capturedSuperProperties = ts.createUnderscoreEscapedMap();
hasSuperElementAccess = false;
+ }
var result;
if (!isArrowFunction) {
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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
if (emitSuperHelpers) {
enableSubstitutionForAsyncMethodsWithSuper();
+ if (ts.hasEntries(capturedSuperProperties)) {
var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
- ts.addStatementsAfterPrologue(statements, [variableStatement]);
+ ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
+ }
}
var block = ts.createBlock(statements, /*multiLine*/ true);
ts.setTextRange(block, node.body);
@@ -69605,8 +70551,10 @@
}
}
enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
+ if (!isArrowFunction) {
capturedSuperProperties = savedCapturedSuperProperties;
hasSuperElementAccess = savedHasSuperElementAccess;
+ }
return result;
}
function transformAsyncFunctionBodyWorker(body, start) {
@@ -69759,7 +70707,7 @@
/* typeParameters */ undefined,
/* parameters */ [],
/* type */ undefined,
- /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name))));
+ /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
if (hasBinding) {
getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(
/* modifiers */ undefined,
@@ -69774,7 +70722,7 @@
/* initializer */ undefined)
],
/* type */ undefined,
- /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v")))));
+ /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v")))));
}
accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter)));
});
@@ -69789,14 +70737,14 @@
], 2 /* Const */));
}
ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
- var awaiterHelper = {
+ ts.awaiterHelper = {
name: "typescript:awaiter",
scoped: false,
priority: 5,
text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
};
function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
- context.requestEmitHelper(awaiterHelper);
+ context.requestEmitHelper(ts.awaiterHelper);
var generatorFunc = ts.createFunctionExpression(
/*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */),
/*name*/ undefined,
@@ -69832,7 +70780,7 @@
/** Enables substitutions for async methods with `super` calls. */
ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
})(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
- function transformESNext(context) {
+ function transformES2018(context) {
var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
var resolver = context.getEmitResolver();
var compilerOptions = context.getCompilerOptions();
@@ -69872,7 +70820,7 @@
return node;
}
function visitorWorker(node, noDestructuringValue) {
- if ((node.transformFlags & 8 /* ContainsESNext */) === 0) {
+ if ((node.transformFlags & 16 /* ContainsES2018 */) === 0) {
return node;
}
switch (node.kind) {
@@ -69916,8 +70864,6 @@
return visitExpressionStatement(node);
case 195 /* ParenthesizedExpression */:
return visitParenthesizedExpression(node, noDestructuringValue);
- case 274 /* CatchClause */:
- return visitCatchClause(node);
case 189 /* PropertyAccessExpression */:
if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) {
capturedSuperProperties.set(node.name.escapedText, true);
@@ -69992,7 +70938,7 @@
return objects;
}
function visitObjectLiteralExpression(node) {
- if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
// spread elements emit like so:
// non-spread elements are chunked together into object literals, and then all are passed to __assign:
// { a, ...o, b } => __assign({a}, o, {b});
@@ -70012,19 +70958,13 @@
function visitParenthesizedExpression(node, noDestructuringValue) {
return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
}
- function visitCatchClause(node) {
- if (!node.variableDeclaration) {
- return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
- }
- return ts.visitEachChild(node, visitor, context);
- }
/**
* Visits a BinaryExpression that contains a destructuring assignment.
*
* @param node A BinaryExpression node.
*/
function visitBinaryExpression(node, noDestructuringValue) {
- if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
}
else if (node.operatorToken.kind === 27 /* CommaToken */) {
@@ -70039,7 +70979,7 @@
*/
function visitVariableDeclaration(node) {
// If we are here it is because the name contains a binding pattern with a rest somewhere in it.
- if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (ts.isBindingPattern(node.name) && node.name.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */);
}
return ts.visitEachChild(node, visitor, context);
@@ -70056,7 +70996,7 @@
* @param node A ForOfStatement.
*/
function visitForOfStatement(node, outermostLabeledStatement) {
- if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.initializer.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
node = transformForOfStatementWithObjectRest(node);
}
if (node.awaitModifier) {
@@ -70153,7 +71093,7 @@
]));
}
function visitParameter(node) {
- if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
// Binding patterns are converted into a generated name and are
// evaluated inside the function body.
return ts.updateParameter(node,
@@ -70266,10 +71206,10 @@
enableSubstitutionForAsyncMethodsWithSuper();
var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
- ts.addStatementsAfterPrologue(statements, [variableStatement]);
+ ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
}
statements.push(returnStatement);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var block = ts.updateBlock(node.body, statements);
if (emitSuperHelpers && hasSuperElementAccess) {
if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
@@ -70295,7 +71235,7 @@
var leadingStatements = endLexicalEnvironment();
if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
- ts.addStatementsAfterPrologue(statements, leadingStatements);
+ ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
ts.addRange(statements, block.statements.slice(statementOffset));
return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
}
@@ -70304,7 +71244,7 @@
function appendObjectRestAssignmentsIfNeeded(statements, node) {
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
- if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (parameter.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
var temp = ts.getGeneratedNameForNode(parameter);
var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp,
/*doNotRecordTempVariablesInLine*/ false,
@@ -70435,8 +71375,8 @@
}
}
}
- ts.transformESNext = transformESNext;
- var assignHelper = {
+ ts.transformES2018 = transformES2018;
+ ts.assignHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
@@ -70447,28 +71387,28 @@
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"),
/*typeArguments*/ undefined, attributesSegments);
}
- context.requestEmitHelper(assignHelper);
+ context.requestEmitHelper(ts.assignHelper);
return ts.createCall(ts.getHelperName("__assign"),
/*typeArguments*/ undefined, attributesSegments);
}
ts.createAssignHelper = createAssignHelper;
- var awaitHelper = {
+ ts.awaitHelper = {
name: "typescript:await",
scoped: false,
text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
};
function createAwaitHelper(context, expression) {
- context.requestEmitHelper(awaitHelper);
+ context.requestEmitHelper(ts.awaitHelper);
return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
}
- var asyncGeneratorHelper = {
+ ts.asyncGeneratorHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
};
function createAsyncGeneratorHelper(context, generatorFunc) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncGeneratorHelper);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncGeneratorHelper);
// Mark this node as originally an async function
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */;
return ts.createCall(ts.getHelperName("__asyncGenerator"),
@@ -70478,24 +71418,24 @@
generatorFunc
]);
}
- var asyncDelegator = {
+ ts.asyncDelegator = {
name: "typescript:asyncDelegator",
scoped: false,
text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
};
function createAsyncDelegatorHelper(context, expression, location) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncDelegator);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncDelegator);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"),
/*typeArguments*/ undefined, [expression]), location);
}
- var asyncValues = {
+ ts.asyncValues = {
name: "typescript:asyncValues",
scoped: false,
text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
};
function createAsyncValuesHelper(context, expression, location) {
- context.requestEmitHelper(asyncValues);
+ context.requestEmitHelper(ts.asyncValues);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"),
/*typeArguments*/ undefined, [expression]), location);
}
@@ -70503,6 +71443,60 @@
/*@internal*/
var ts;
(function (ts) {
+ function transformES2019(context) {
+ return ts.chainBundle(transformSourceFile);
+ function transformSourceFile(node) {
+ if (node.isDeclarationFile) {
+ return node;
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitor(node) {
+ if ((node.transformFlags & 8 /* ContainsES2019 */) === 0) {
+ return node;
+ }
+ switch (node.kind) {
+ case 274 /* CatchClause */:
+ return visitCatchClause(node);
+ default:
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ function visitCatchClause(node) {
+ if (!node.variableDeclaration) {
+ return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ ts.transformES2019 = transformES2019;
+})(ts || (ts = {}));
+/*@internal*/
+var ts;
+(function (ts) {
+ function transformESNext(context) {
+ return ts.chainBundle(transformSourceFile);
+ function transformSourceFile(node) {
+ if (node.isDeclarationFile) {
+ return node;
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitor(node) {
+ if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
+ return node;
+ }
+ switch (node.kind) {
+ default:
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ }
+ ts.transformESNext = transformESNext;
+})(ts || (ts = {}));
+/*@internal*/
+var ts;
+(function (ts) {
function transformJsx(context) {
var compilerOptions = context.getCompilerOptions();
var currentSourceFile;
@@ -70522,7 +71516,7 @@
return visited;
}
function visitor(node) {
- if (node.transformFlags & 4 /* ContainsJsx */) {
+ if (node.transformFlags & 2 /* ContainsJsx */) {
return visitorWorker(node);
}
else {
@@ -70639,7 +71633,7 @@
}
}
function visitJsxText(node) {
- var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, /*includeTrivia*/ true));
+ var fixed = fixupWhitespaceAndDecodeEntities(node.text);
return fixed === undefined ? undefined : ts.createLiteral(fixed);
}
/**
@@ -71024,7 +72018,7 @@
return ts.visitEachChild(node, visitor, context);
}
function visitor(node) {
- if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) {
+ if ((node.transformFlags & 64 /* ContainsES2016 */) === 0) {
return node;
}
switch (node.kind) {
@@ -71104,30 +72098,6 @@
Jump[Jump["Continue"] = 4] = "Continue";
Jump[Jump["Return"] = 8] = "Return";
})(Jump || (Jump = {}));
- var SuperCaptureResult;
- (function (SuperCaptureResult) {
- /**
- * A capture may have been added for calls to 'super', but
- * the caller should emit subsequent statements normally.
- */
- SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement";
- /**
- * A call to 'super()' got replaced with a capturing statement like:
- *
- * var _this = _super.call(...) || this;
- *
- * Callers should skip the current statement.
- */
- SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture";
- /**
- * A call to 'super()' got replaced with a capturing statement like:
- *
- * return _super.call(...) || this;
- *
- * Callers should skip the current statement and avoid any returns of '_this'.
- */
- SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn";
- })(SuperCaptureResult || (SuperCaptureResult = {}));
// Facts we track as we traverse the tree
var HierarchyFacts;
(function (HierarchyFacts) {
@@ -71148,12 +72118,12 @@
HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement";
HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement";
HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper";
- HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName";
// NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
+ // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
//
// Ancestor masks
//
- HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
+ HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 8191] = "AncestorFactsMask";
// We are always in *some* kind of block scope, but only specific block-scope containers are
// top-level or Blocks.
HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
@@ -71163,16 +72133,16 @@
HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes";
// Functions, methods, and accessors are both new lexical scopes and new block scopes.
HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
- HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
+ HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 8094] = "FunctionExcludes";
HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
- HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
+ HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 8086] = "AsyncFunctionBodyExcludes";
// Arrow functions are lexically scoped to their container, but are new block scopes.
HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
- HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes";
+ HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 8064] = "ArrowFunctionExcludes";
// Constructors are both new lexical scopes and new block scopes. Constructors are also
// always considered non-static members of a class.
HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
- HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
+ HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 8086] = "ConstructorExcludes";
// 'do' and 'while' statements are not block scopes. We track that the subtree is contained
// within an IterationStatement to indicate whether the embedded statement is an
// IterationStatementBlock.
@@ -71190,19 +72160,17 @@
HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes";
HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes";
- // Computed property names track subtree flags differently than their containing members.
- HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes";
- HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes";
//
// Subtree facts
//
- HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
- HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName";
+ HierarchyFacts[HierarchyFacts["NewTarget"] = 8192] = "NewTarget";
+ HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 16384] = "CapturedLexicalThis";
//
// Subtree masks
//
- HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
- HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask";
+ HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -8192] = "SubtreeFactsMask";
+ HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
+ HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 24576] = "FunctionSubtreeExcludes";
})(HierarchyFacts || (HierarchyFacts = {}));
function transformES2015(context) {
var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
@@ -71251,7 +72219,7 @@
*/
function enterSubtree(excludeFacts, includeFacts) {
var ancestorFacts = hierarchyFacts;
- hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 8191 /* AncestorFactsMask */;
return ancestorFacts;
}
/**
@@ -71262,7 +72230,7 @@
* @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
*/
function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
- hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -8192 /* SubtreeFactsMask */ | ancestorFacts;
}
function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0
@@ -71284,12 +72252,6 @@
return node;
}
}
- function functionBodyVisitor(node) {
- if (shouldVisitNode(node)) {
- return visitBlock(node, /*isFunctionBody*/ true);
- }
- return node;
- }
function callExpressionVisitor(node) {
if (node.kind === 98 /* SuperKeyword */) {
return visitSuperKeyword(/*isExpressionOfCall*/ true);
@@ -71396,18 +72358,19 @@
}
function visitSourceFile(node) {
var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
+ var prologue = [];
var statements = [];
startLexicalEnvironment();
- var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false);
- addCaptureThisForNodeIfNeeded(statements, node);
- statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor);
+ var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false);
+ statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor);
ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
if (taggedTemplateStringDeclarations) {
statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureThisForNodeIfNeeded(prologue, node);
exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
- return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
+ return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
}
function visitSwitchStatement(node) {
if (convertedLoopState !== undefined) {
@@ -71447,6 +72410,9 @@
return ts.visitEachChild(node, visitor, context);
}
function visitThisKeyword(node) {
+ if (hierarchyFacts & 2 /* ArrowFunction */) {
+ hierarchyFacts |= 16384 /* CapturedLexicalThis */;
+ }
if (convertedLoopState) {
if (hierarchyFacts & 2 /* ArrowFunction */) {
// if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
@@ -71660,7 +72626,7 @@
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
ts.setEmitFlags(block, 1536 /* NoComments */);
return block;
@@ -71688,7 +72654,7 @@
function addConstructor(statements, node, extendsClauseElement) {
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
+ var ancestorFacts = enterSubtree(8086 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
var constructor = ts.getFirstConstructorWithBody(node);
var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
var constructorFunction = ts.createFunctionDeclaration(
@@ -71702,7 +72668,7 @@
ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
}
statements.push(constructorFunction);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
}
/**
@@ -71721,6 +72687,24 @@
return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
|| [];
}
+ function createDefaultConstructorBody(node, isDerivedClass) {
+ // We must be here because the user didn't write a constructor
+ // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
+ // If that's the case we can just immediately return the result of a 'super()' call.
+ var statements = [];
+ resumeLexicalEnvironment();
+ ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
+ if (isDerivedClass) {
+ // return _super !== null && _super.apply(this, arguments) || this;
+ statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
+ }
+ var statementsArray = ts.createNodeArray(statements);
+ ts.setTextRange(statementsArray, node.members);
+ var block = ts.createBlock(statementsArray, /*multiLine*/ true);
+ ts.setTextRange(block, node);
+ ts.setEmitFlags(block, 1536 /* NoComments */);
+ return block;
+ }
/**
* Transforms the body of a constructor declaration of a class.
*
@@ -71731,59 +72715,137 @@
* synthesized `super` call.
*/
function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
+ // determine whether the class is known syntactically to be a derived class (e.g. a
+ // class that extends a value that is not syntactically known to be `null`).
+ var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */;
+ // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
+ // representation:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base { }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // return _super.apply(this, arguments) || this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ if (!constructor)
+ return createDefaultConstructorBody(node, isDerivedClass);
+ // The prologue will contain all leading standard and custom prologue statements added by this transform
+ var prologue = [];
var statements = [];
resumeLexicalEnvironment();
- var statementOffset = -1;
- if (hasSynthesizedSuper) {
// If a super call has already been synthesized,
// we're going to assume that we should just transform everything after that.
// The assumption is that no prior step in the pipeline has added any prologue directives.
- statementOffset = 0;
- }
- else if (constructor) {
- statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false);
- }
- if (constructor) {
+ var statementOffset = 0;
+ if (!hasSynthesizedSuper)
+ statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false);
addDefaultValueAssignmentsIfNeeded(statements, constructor);
addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
- if (!hasSynthesizedSuper) {
- // If no super call has been synthesized, emit custom prologue directives.
+ if (!hasSynthesizedSuper)
statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
+ // If the first statement is a call to `super()`, visit the statement directly
+ var superCallExpression;
+ if (hasSynthesizedSuper) {
+ superCallExpression = createDefaultSuperCallOrThis();
}
- ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!");
+ else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
+ var firstStatement = constructor.body.statements[statementOffset];
+ if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
+ superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
}
- // determine whether the class is known syntactically to be a derived class (e.g. a
- // class that extends a value that is not syntactically known to be `null`).
- var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */;
- var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset);
- // The last statement expression was replaced. Skip it.
- if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) {
- statementOffset++;
}
- if (constructor) {
- if (superCaptureStatus === 1 /* ReplaceSuperCapture */) {
+ if (superCallExpression) {
hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */;
+ statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
}
+ // visit the remaining statements
ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
+ if (isDerivedClass) {
+ if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 2048 /* ContainsLexicalThis */)) {
+ // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
+ // following representation:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base {
+ // constructor() {
+ // super("foo");
+ // }
+ // }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // return _super.call(this, "foo") || this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
+ var returnStatement = ts.createReturn(superCallExpression);
+ ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
+ ts.setEmitFlags(superCall, 1536 /* NoComments */);
+ statements.push(returnStatement);
}
- // Return `_this` unless we're sure enough that it would be pointless to add a return statement.
- // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return.
- if (isDerivedClass
- && superCaptureStatus !== 2 /* ReplaceWithReturn */
- && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) {
+ else {
+ // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base {
+ // constructor() {
+ // super("foo");
+ // this.x = 1;
+ // }
+ // }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // var _this = _super.call(this, "foo") || this;
+ // _this.x = 1;
+ // return _this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ // Since the `super()` call was the first statement, we insert the `this` capturing call to
+ // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
+ insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
+ if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
- if (constructor) {
- prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false);
}
- var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements),
- /*location*/ constructor ? constructor.body.statements : node.members),
- /*multiLine*/ true);
- ts.setTextRange(block, constructor ? constructor.body : node);
- if (!constructor) {
- ts.setEmitFlags(block, 1536 /* NoComments */);
}
+ else {
+ // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
+ // captured when necessitated by an arrow function capturing the lexical `this`:
+ //
+ // ```
+ // // es2015
+ // class C {}
+ //
+ // // es5
+ // var C = (function () {
+ // function C() {
+ // }
+ // return C;
+ // })();
+ // ```
+ insertCaptureThisForNodeIfNeeded(prologue, constructor);
+ }
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)),
+ /*location*/ constructor.body.statements),
+ /*multiLine*/ true);
+ ts.setTextRange(block, constructor.body);
return block;
}
/**
@@ -71813,83 +72875,6 @@
}
return false;
}
- /**
- * Declares a `_this` variable for derived classes and for when arrow functions capture `this`.
- *
- * @returns The new statement offset into the `statements` array.
- */
- function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) {
- // If this isn't a derived class, just capture 'this' for arrow functions if necessary.
- if (!isDerivedClass) {
- if (ctor) {
- addCaptureThisForNodeIfNeeded(statements, ctor);
- }
- return 0 /* NoReplacement */;
- }
- // We must be here because the user didn't write a constructor
- // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
- // If that's the case we can just immediately return the result of a 'super()' call.
- if (!ctor) {
- statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
- return 2 /* ReplaceWithReturn */;
- }
- // The constructor exists, but it and the 'super()' call it contains were generated
- // for something like property initializers.
- // Create a captured '_this' variable and assume it will subsequently be used.
- if (hasSynthesizedSuper) {
- captureThisForNode(statements, ctor, createDefaultSuperCallOrThis());
- enableSubstitutionsForCapturedThis();
- return 1 /* ReplaceSuperCapture */;
- }
- // Most of the time, a 'super' call will be the first real statement in a constructor body.
- // In these cases, we'd like to transform these into a *single* statement instead of a declaration
- // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer,
- // we'd get:
- //
- // var _this;
- // _this = _super.call(...) || this;
- //
- // instead of
- //
- // var _this = _super.call(...) || this;
- //
- // Additionally, if the 'super()' call is the last statement, we should just avoid capturing
- // entirely and immediately return the result like so:
- //
- // return _super.call(...) || this;
- //
- var firstStatement;
- var superCallExpression;
- var ctorStatements = ctor.body.statements;
- if (statementOffset < ctorStatements.length) {
- firstStatement = ctorStatements[statementOffset];
- if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) {
- superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
- }
- }
- // Return the result if we have an immediate super() call on the last statement,
- // but only if the constructor itself doesn't use 'this' elsewhere.
- if (superCallExpression
- && statementOffset === ctorStatements.length - 1
- && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) {
- var returnStatement = ts.createReturn(superCallExpression);
- if (superCallExpression.kind !== 204 /* BinaryExpression */
- || superCallExpression.left.kind !== 191 /* 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.
- ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */)));
- statements.push(returnStatement);
- return 2 /* ReplaceWithReturn */;
- }
- // Perform the capture.
- 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 */;
- }
- return 0 /* NoReplacement */;
- }
function createActualThis() {
return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
}
@@ -71935,14 +72920,9 @@
return node;
}
}
- /**
- * Gets a value indicating whether we need to add default value assignments for a
- * function-like node.
- *
- * @param node A function-like node.
- */
- function shouldAddDefaultValueAssignments(node) {
- return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0;
+ function hasDefaultValueOrBindingPattern(node) {
+ return node.initializer !== undefined
+ || ts.isBindingPattern(node.name);
}
/**
* Adds statements to the body of a function-like node if it contains parameters with
@@ -71952,9 +72932,10 @@
* @param node A function-like node.
*/
function addDefaultValueAssignmentsIfNeeded(statements, node) {
- if (!shouldAddDefaultValueAssignments(node)) {
- return;
+ if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
+ return false;
}
+ var added = false;
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
@@ -71964,12 +72945,14 @@
continue;
}
if (ts.isBindingPattern(name)) {
- addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer);
+ added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
}
else if (initializer) {
- addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
+ insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
+ added = true;
}
}
+ return added;
}
/**
* Adds statements to the body of a function-like node for parameters with binding patterns
@@ -71979,18 +72962,20 @@
* @param name The name of the parameter.
* @param initializer The initializer for the parameter.
*/
- function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
- var temp = ts.getGeneratedNameForNode(parameter);
+ function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
// In cases where a binding pattern is simply '[]' or '{}',
// we usually don't want to emit a var declaration; however, in the presence
// of an initializer, we must emit that expression to preserve side effects.
if (name.elements.length > 0) {
- statements.push(ts.setEmitFlags(ts.createVariableStatement(
- /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */));
+ ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(
+ /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
+ return true;
}
else if (initializer) {
- statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
+ ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
+ return true;
}
+ return false;
}
/**
* Adds statements to the body of a function-like node for parameters with initializers.
@@ -72000,7 +72985,7 @@
* @param name The name of the parameter.
* @param initializer The initializer for the parameter.
*/
- function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
+ function insertDefaultValueAssignmentForInitializer(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.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 */))
@@ -72008,7 +72993,7 @@
ts.startOnNewLine(statement);
ts.setTextRange(statement, parameter);
ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
- statements.push(statement);
+ ts.insertStatementAfterCustomPrologue(statements, statement);
}
/**
* Gets a value indicating whether we need to add statements to handle a rest parameter.
@@ -72031,9 +73016,10 @@
* synthesized call to `super`
*/
function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
+ var prologueStatements = [];
var parameter = ts.lastOrUndefined(node.parameters);
if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
- return;
+ return false;
}
// `declarationName` is the name of the local declaration for the parameter.
var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined);
@@ -72043,7 +73029,7 @@
var restIndex = node.parameters.length - 1;
var temp = ts.createLoopVariable();
// var param = [];
- statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
+ prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList([
ts.createVariableDeclaration(declarationName,
/*type*/ undefined, ts.createArrayLiteral([]))
@@ -72062,25 +73048,30 @@
]));
ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
ts.startOnNewLine(forStatement);
- statements.push(forStatement);
+ prologueStatements.push(forStatement);
if (parameter.name.kind !== 72 /* Identifier */) {
// do the actual destructuring of the rest parameter if necessary
- statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
+ prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
}
+ ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
+ return true;
}
/**
* Adds a statement to capture the `this` of a function declaration if it is needed.
+ * NOTE: This must be executed *after* the subtree has been visited.
*
* @param statements The statements for the new function body.
* @param node A node.
*/
- function addCaptureThisForNodeIfNeeded(statements, node) {
- if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) {
- captureThisForNode(statements, node, ts.createThis());
+ function insertCaptureThisForNodeIfNeeded(statements, node) {
+ if (hierarchyFacts & 16384 /* CapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) {
+ insertCaptureThisForNode(statements, node, ts.createThis());
+ return true;
}
+ return false;
}
- function captureThisForNode(statements, node, initializer) {
+ function insertCaptureThisForNode(statements, node, initializer) {
enableSubstitutionsForCapturedThis();
var captureThisStatement = ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList([
@@ -72089,10 +73080,10 @@
]));
ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
ts.setSourceMapRange(captureThisStatement, node);
- statements.push(captureThisStatement);
+ ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
}
- function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
- if (hierarchyFacts & 16384 /* NewTarget */) {
+ function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
+ if (hierarchyFacts & 8192 /* NewTarget */) {
var newTarget = void 0;
switch (node.kind) {
case 197 /* ArrowFunction */:
@@ -72123,10 +73114,11 @@
ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"),
/*type*/ undefined, newTarget)
]));
+ ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
if (copyOnWrite) {
- return [captureNewTargetStatement].concat(statements);
+ statements = statements.slice();
}
- statements.unshift(captureNewTargetStatement);
+ ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
}
return statements;
}
@@ -72178,7 +73170,6 @@
* @param member The MethodDeclaration node.
*/
function transformClassMethodDeclarationToStatement(receiver, member, container) {
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
var commentRange = ts.getCommentRange(member);
var sourceMapRange = ts.getSourceMapRange(member);
var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name);
@@ -72193,7 +73184,6 @@
// No source map should be emitted for this statement to align with the
// old emitter.
ts.setEmitFlags(statement, 48 /* NoSourceMap */);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return statement;
}
/**
@@ -72219,7 +73209,6 @@
*/
function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
// To align with source maps in the old emitter, the receiver and property name
// arguments are both mapped contiguously to the accessor name.
var target = ts.getMutableClone(receiver);
@@ -72255,7 +73244,6 @@
if (startsOnNewLine) {
ts.startOnNewLine(call);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return call;
}
/**
@@ -72264,12 +73252,12 @@
* @param node An ArrowFunction node.
*/
function visitArrowFunction(node) {
- if (node.transformFlags & 8192 /* ContainsLexicalThis */) {
- enableSubstitutionsForCapturedThis();
+ if (node.transformFlags & 2048 /* ContainsLexicalThis */) {
+ hierarchyFacts |= 16384 /* CapturedLexicalThis */;
}
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
+ var ancestorFacts = enterSubtree(8064 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
var func = ts.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
@@ -72279,7 +73267,11 @@
ts.setTextRange(func, node);
ts.setOriginalNode(func, node);
ts.setEmitFlags(func, 8 /* CapturesThis */);
- exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
+ if (hierarchyFacts & 16384 /* CapturedLexicalThis */) {
+ enableSubstitutionsForCapturedThis();
+ }
+ // If an arrow function contains
+ exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return func;
}
@@ -72290,18 +73282,16 @@
*/
function visitFunctionExpression(node) {
var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
- ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
- : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ ? enterSubtree(8086 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
+ : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & 64 /* ES2015 */
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
- var name = hierarchyFacts & 16384 /* NewTarget */
+ var body = transformFunctionBody(node);
+ var name = hierarchyFacts & 8192 /* NewTarget */
? ts.getLocalName(node)
: node.name;
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.updateFunctionExpression(node,
/*modifiers*/ undefined, node.asteriskToken, name,
@@ -72316,15 +73306,13 @@
function visitFunctionDeclaration(node) {
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & 64 /* ES2015 */
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
- var name = hierarchyFacts & 16384 /* NewTarget */
+ var body = transformFunctionBody(node);
+ var name = hierarchyFacts & 8192 /* NewTarget */
? ts.getLocalName(node)
: node.name;
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.updateFunctionDeclaration(node,
/*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name,
@@ -72342,14 +73330,14 @@
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
- ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
- : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ ? enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
+ : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var parameters = ts.visitParameterList(node.parameters, visitor, context);
var body = transformFunctionBody(node);
- if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) {
+ if (hierarchyFacts & 8192 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) {
name = ts.getGeneratedNameForNode(node);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
/*modifiers*/ undefined, node.asteriskToken, name,
@@ -72367,7 +73355,7 @@
var singleLine = false; // indicates whether the block *may* be emitted as a single line
var statementsLocation;
var closeBraceLocation;
- var leadingStatements = [];
+ var prologue = [];
var statements = [];
var body = node.body;
var statementOffset;
@@ -72375,14 +73363,13 @@
if (ts.isBlock(body)) {
// ensureUseStrict is false because no new prologue-directive should be added.
// addStandardPrologue will put already-existing directives at the beginning of the target statement-array
- statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false);
+ statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false);
}
- addCaptureThisForNodeIfNeeded(leadingStatements, node);
- addDefaultValueAssignmentsIfNeeded(leadingStatements, node);
- addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false);
+ multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
+ multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
if (ts.isBlock(body)) {
// addCustomPrologue puts already-existing directives at the beginning of the target statement-array
- statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor);
+ statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
statementsLocation = body.statements;
ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
// If the original body was a multi-line block, this must be a multi-line block.
@@ -72416,14 +73403,19 @@
// source map location for the close brace.
closeBraceLocation = body;
}
- var lexicalEnvironment = context.endLexicalEnvironment();
- ts.addStatementsAfterPrologue(statements, lexicalEnvironment);
- prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false);
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
+ insertCaptureThisForNodeIfNeeded(prologue, node);
// If we added any final generated statements, this must be a multi-line block
- if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) {
+ if (ts.some(prologue)) {
multiLine = true;
}
- var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine);
+ statements.unshift.apply(statements, prologue);
+ if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
+ // no changes were made, preserve the tree
+ return body;
+ }
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
ts.setTextRange(block, node.body);
if (!multiLine && singleLine) {
ts.setEmitFlags(block, 1 /* SingleLine */);
@@ -72434,11 +73426,6 @@
ts.setOriginalNode(block, node.body);
return block;
}
- function visitFunctionBodyDownLevel(node) {
- var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context);
- return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)),
- /*location*/ updated.statements));
- }
function visitBlock(node, isFunctionBody) {
if (isFunctionBody) {
// A function body is not a block scope.
@@ -72543,7 +73530,7 @@
* @param node A VariableDeclarationList node.
*/
function visitVariableDeclarationList(node) {
- if (node.transformFlags & 64 /* ES2015 */) {
+ if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 65536 /* ContainsBindingPattern */) {
if (node.flags & 3 /* BlockScoped */) {
enableSubstitutionsForBlockScopedBindings();
}
@@ -72556,7 +73543,7 @@
ts.setCommentRange(declarationList, node);
// If the first or last declaration is a binding pattern, we need to modify
// the source map range for the declaration list.
- if (node.transformFlags & 2097152 /* ContainsBindingPattern */
+ if (node.transformFlags & 65536 /* ContainsBindingPattern */
&& (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
}
@@ -72878,7 +73865,7 @@
var numInitialPropertiesWithoutYield = numProperties;
for (var i = 0; i < numProperties; i++) {
var property = properties[i];
- if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
+ if ((property.transformFlags & 131072 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
&& i < numInitialPropertiesWithoutYield) {
numInitialPropertiesWithoutYield = i;
}
@@ -73154,7 +74141,7 @@
*/
function createFunctionForInitializerOfForStatement(node, currentState) {
var functionName = ts.createUniqueName("_loop_init");
- var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ var containsYield = (node.initializer.transformFlags & 131072 /* ContainsYield */) !== 0;
var emitFlags = 0 /* None */;
if (currentState.containsLexicalThis)
emitFlags |= 8 /* CapturesThis */;
@@ -73259,11 +74246,11 @@
statements.push(statement);
}
copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
- ts.addStatementsAfterPrologue(statements, lexicalEnvironment);
+ ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
var loopBody = ts.createBlock(statements, /*multiLine*/ true);
if (ts.isBlock(statement))
ts.setOriginalNode(loopBody, statement);
- var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ var containsYield = (node.statement.transformFlags & 131072 /* ContainsYield */) !== 0;
var emitFlags = 0;
if (currentState.containsLexicalThis)
emitFlags |= 8 /* CapturesThis */;
@@ -73495,13 +74482,11 @@
* @param receiver The receiver for the assignment.
*/
function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
ts.setTextRange(expression, method);
if (startsOnNewLine) {
ts.startOnNewLine(expression);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return expression;
}
function visitCatchClause(node) {
@@ -73553,19 +74538,17 @@
ts.Debug.assert(!ts.isComputedPropertyName(node.name));
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var updated;
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */)
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
+ var body = transformFunctionBody(node);
if (node.kind === 158 /* GetAccessor */) {
updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
}
else {
updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return updated;
}
@@ -73579,10 +74562,7 @@
/*location*/ node);
}
function visitComputedPropertyName(node) {
- var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */);
- var updated = ts.visitEachChild(node, visitor, context);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */);
- return updated;
+ return ts.visitEachChild(node, visitor, context);
}
/**
* Visits a YieldExpression node.
@@ -73599,7 +74579,7 @@
* @param node An ArrayLiteralExpression node.
*/
function visitArrayLiteralExpression(node) {
- if (node.transformFlags & 64 /* ES2015 */) {
+ if (ts.some(node.elements, ts.isSpreadElement)) {
// We are here because we contain a SpreadElementExpression.
return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
}
@@ -73614,7 +74594,10 @@
if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
return visitTypeScriptClassWrapper(node);
}
- if (node.transformFlags & 64 /* ES2015 */) {
+ var expression = ts.skipOuterExpressions(node.expression);
+ if (expression.kind === 98 /* SuperKeyword */ ||
+ ts.isSuperProperty(expression) ||
+ ts.some(node.arguments, ts.isSpreadElement)) {
return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
}
return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression),
@@ -73735,7 +74718,7 @@
function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
// We are here either because SuperKeyword was used somewhere in the expression, or
// because we contain a SpreadElementExpression.
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */ ||
+ if (node.transformFlags & 4096 /* ContainsRestOrSpread */ ||
node.expression.kind === 98 /* SuperKeyword */ ||
ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
@@ -73743,7 +74726,7 @@
ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
}
var resultingCall = void 0;
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */) {
+ if (node.transformFlags & 4096 /* ContainsRestOrSpread */) {
// [source]
// f(...a, b)
// x.m(...a, b)
@@ -73757,7 +74740,7 @@
// _super.apply(this, a.concat([b]))
// _super.m.apply(this, a.concat([b]))
// _super.prototype.m.apply(this, a.concat([b]))
- resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
+ resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
}
else {
// [source]
@@ -73769,13 +74752,11 @@
// _super.call(this, a)
// _super.m.call(this, a)
// _super.prototype.m.call(this, a)
- resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
+ resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
/*location*/ node);
}
if (node.expression.kind === 98 /* SuperKeyword */) {
- var actualThis = ts.createThis();
- ts.setEmitFlags(actualThis, 4 /* NoSubstitution */);
- var initializer = ts.createLogicalOr(resultingCall, actualThis);
+ var initializer = ts.createLogicalOr(resultingCall, createActualThis());
resultingCall = assignToCapturedThis
? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
: initializer;
@@ -73790,7 +74771,7 @@
* @param node A NewExpression node.
*/
function visitNewExpression(node) {
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */) {
+ if (ts.some(node.arguments, ts.isSpreadElement)) {
// We are here because we contain a SpreadElementExpression.
// [source]
// new C(...a)
@@ -74053,12 +75034,7 @@
}
function visitMetaProperty(node) {
if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") {
- if (hierarchyFacts & 8192 /* ComputedPropertyName */) {
- hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */;
- }
- else {
- hierarchyFacts |= 16384 /* NewTarget */;
- }
+ hierarchyFacts |= 8192 /* NewTarget */;
return ts.createFileLevelUniqueName("_newTarget");
}
return node;
@@ -74073,7 +75049,7 @@
function onEmitNode(hint, node, emitCallback) {
if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
// If we are tracking a captured `this`, keep track of the enclosing function.
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
: 65 /* FunctionIncludes */);
previousOnEmitNode(hint, node, emitCallback);
@@ -74253,7 +75229,7 @@
}
ts.transformES2015 = transformES2015;
function createExtendsHelper(context, name) {
- context.requestEmitHelper(extendsHelper);
+ context.requestEmitHelper(ts.extendsHelper);
return ts.createCall(ts.getHelperName("__extends"),
/*typeArguments*/ undefined, [
name,
@@ -74261,20 +75237,20 @@
]);
}
function createTemplateObjectHelper(context, cooked, raw) {
- context.requestEmitHelper(templateObjectHelper);
+ context.requestEmitHelper(ts.templateObjectHelper);
return ts.createCall(ts.getHelperName("__makeTemplateObject"),
/*typeArguments*/ undefined, [
cooked,
raw
]);
}
- var extendsHelper = {
+ ts.extendsHelper = {
name: "typescript:extends",
scoped: false,
priority: 0,
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 = {
+ ts.templateObjectHelper = {
name: "typescript:makeTemplateObject",
scoped: false,
priority: 0,
@@ -74621,7 +75597,7 @@
var withBlockStack; // A stack containing `with` blocks.
return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
- if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
+ if (node.isDeclarationFile || (node.transformFlags & 256 /* ContainsGenerator */) === 0) {
return node;
}
var visited = ts.visitEachChild(node, visitor, context);
@@ -74641,10 +75617,10 @@
else if (inGeneratorFunctionBody) {
return visitJavaScriptInGeneratorFunctionBody(node);
}
- else if (transformFlags & 256 /* Generator */) {
+ else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
return visitGenerator(node);
}
- else if (transformFlags & 512 /* ContainsGenerator */) {
+ else if (transformFlags & 256 /* ContainsGenerator */) {
return ts.visitEachChild(node, visitor, context);
}
else {
@@ -74697,10 +75673,10 @@
case 230 /* ReturnStatement */:
return visitReturnStatement(node);
default:
- if (node.transformFlags & 4194304 /* ContainsYield */) {
+ if (node.transformFlags & 131072 /* ContainsYield */) {
return visitJavaScriptContainingYield(node);
}
- else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) {
+ else if (node.transformFlags & (256 /* ContainsGenerator */ | 262144 /* ContainsHoistedDeclarationOrCompletion */)) {
return ts.visitEachChild(node, visitor, context);
}
else {
@@ -74876,7 +75852,7 @@
var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
transformAndEmitStatements(body.statements, statementOffset);
var buildResult = build();
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
statements.push(ts.createReturn(buildResult));
// Restore previous generator state
inGeneratorFunctionBody = savedInGeneratorFunctionBody;
@@ -74903,7 +75879,7 @@
* @param node The node to visit.
*/
function visitVariableStatement(node) {
- if (node.transformFlags & 4194304 /* ContainsYield */) {
+ if (node.transformFlags & 131072 /* ContainsYield */) {
transformAndEmitVariableDeclarationList(node.declarationList);
return undefined;
}
@@ -75961,7 +76937,7 @@
}
}
function containsYield(node) {
- return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ return !!node && (node.transformFlags & 131072 /* ContainsYield */) !== 0;
}
function countInitialNodesWithoutYield(nodes) {
var numNodes = nodes.length;
@@ -76968,7 +77944,7 @@
}
ts.transformGenerators = transformGenerators;
function createGeneratorHelper(context, body) {
- context.requestEmitHelper(generatorHelper);
+ context.requestEmitHelper(ts.generatorHelper);
return ts.createCall(ts.getHelperName("__generator"),
/*typeArguments*/ undefined, [ts.createThis(), body]);
}
@@ -77031,7 +78007,7 @@
// entering a finally block.
//
// For examples of how these are used, see the comments in ./transformers/generators.ts
- var generatorHelper = {
+ ts.generatorHelper = {
name: "typescript:generator",
scoped: false,
priority: 6,
@@ -77064,7 +78040,7 @@
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* 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.
@@ -77080,7 +78056,7 @@
function transformSourceFile(node) {
if (node.isDeclarationFile ||
!(ts.isEffectiveExternalModule(node, compilerOptions) ||
- node.transformFlags & 16777216 /* ContainsDynamicImport */ ||
+ node.transformFlags & 524288 /* ContainsDynamicImport */ ||
(ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
return node;
}
@@ -77117,7 +78093,7 @@
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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(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
@@ -77343,7 +78319,7 @@
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
// End the lexical environment for the module body
// and merge any new lexical declarations.
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var body = ts.createBlock(statements, /*multiLine*/ true);
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
// If we have any `export * from ...` declarations
@@ -77406,9 +78382,9 @@
return visitFunctionDeclaration(node);
case 240 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
@@ -77417,13 +78393,13 @@
function moduleExpressionElementVisitor(node) {
// This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
// as export/import statements are only transformed at the top level of a file.
- if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) {
+ if (!(node.transformFlags & 524288 /* ContainsDynamicImport */) && !(node.transformFlags & 512 /* ContainsDestructuringAssignment */)) {
return node;
}
if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
- else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) {
+ else if (ts.isDestructuringAssignment(node)) {
return visitDestructuringAssignment(node);
}
else {
@@ -77484,7 +78460,7 @@
}
function visitImportCallExpression(node) {
var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
- var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */);
+ var containsLexicalThis = !!(node.transformFlags & 2048 /* ContainsLexicalThis */);
switch (compilerOptions.module) {
case ts.ModuleKind.AMD:
return createImportCallExpressionAMD(argument, containsLexicalThis);
@@ -77566,7 +78542,7 @@
}
var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]);
}
return promise;
@@ -77580,7 +78556,7 @@
var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
}
var func;
@@ -77614,11 +78590,11 @@
return innerExpr;
}
if (ts.getImportNeedsImportStarHelper(node)) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
}
if (ts.getImportNeedsImportDefaultHelper(node)) {
- context.requestEmitHelper(importDefaultHelper);
+ context.requestEmitHelper(ts.importDefaultHelper);
return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
}
return innerExpr;
@@ -78187,7 +79163,7 @@
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
currentSourceFile = node;
currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
noSubstitution = [];
@@ -78275,7 +79251,7 @@
}
if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)),
/*location*/ node);
}
@@ -78401,13 +79377,13 @@
text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
};
// emit helper for `import * as Name from "foo"`
- var importStarHelper = {
+ ts.importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
// emit helper for `import Name from "foo"`
- var importDefaultHelper = {
+ ts.importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
@@ -78430,7 +79406,7 @@
context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols.
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* 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.
@@ -78449,7 +79425,7 @@
* @param node The SourceFile node.
*/
function transformSourceFile(node) {
- if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) {
+ if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 524288 /* ContainsDynamicImport */)) {
return node;
}
var id = ts.getOriginalNodeId(node);
@@ -78615,7 +79591,7 @@
// 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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
var moduleObject = ts.createObjectLiteral([
ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
@@ -79000,7 +79976,7 @@
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 === 279 /* SourceFile */
+ && (enclosingBlockScopedContainer.kind === 284 /* SourceFile */
|| (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
}
/**
@@ -79343,9 +80319,9 @@
return visitCatchClause(node);
case 218 /* Block */:
return visitBlock(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -79527,14 +80503,13 @@
* @param node The node to visit.
*/
function destructuringAndImportCallVisitor(node) {
- if (node.transformFlags & 1024 /* DestructuringAssignment */
- && node.kind === 204 /* BinaryExpression */) {
+ if (ts.isDestructuringAssignment(node)) {
return visitDestructuringAssignment(node);
}
else if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
- else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) {
+ else if ((node.transformFlags & 512 /* ContainsDestructuringAssignment */) || (node.transformFlags & 524288 /* ContainsDynamicImport */)) {
return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
}
else {
@@ -79593,7 +80568,7 @@
}
else if (ts.isIdentifier(node)) {
var container = resolver.getReferencedExportContainer(node);
- return container !== undefined && container.kind === 279 /* SourceFile */;
+ return container !== undefined && container.kind === 284 /* SourceFile */;
}
else {
return false;
@@ -79626,7 +80601,7 @@
* @param emitCallback A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
var id = ts.getOriginalNodeId(node);
currentSourceFile = node;
moduleInfo = moduleInfoMap[id];
@@ -79835,7 +80810,7 @@
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
}
exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
@@ -79874,7 +80849,7 @@
var previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- context.enableEmitNotification(279 /* SourceFile */);
+ context.enableEmitNotification(284 /* SourceFile */);
context.enableSubstitution(72 /* Identifier */);
var currentSourceFile;
return ts.chainBundle(transformSourceFile);
@@ -79984,7 +80959,8 @@
ts.isImportEqualsDeclaration(node) ||
ts.isTypeAliasDeclaration(node) ||
ts.isConstructorDeclaration(node) ||
- ts.isIndexSignatureDeclaration(node);
+ ts.isIndexSignatureDeclaration(node) ||
+ ts.isPropertyAccessExpression(node);
}
ts.canProduceDiagnostics = canProduceDiagnostics;
function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
@@ -80058,7 +81034,7 @@
}
ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
function createGetSymbolAccessibilityDiagnosticForNode(node) {
- if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
+ if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
return getVariableDeclarationTypeVisibilityError;
}
else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
@@ -80098,7 +81074,7 @@
}
// This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
// The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
- else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ ||
+ else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 189 /* PropertyAccessExpression */ || node.kind === 153 /* PropertySignature */ ||
(node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
// TODO(jfreeman): Deal with computed properties in error reporting.
if (ts.hasModifier(node, 32 /* Static */)) {
@@ -80303,6 +81279,9 @@
case 241 /* InterfaceDeclaration */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
break;
+ case 181 /* MappedType */:
+ diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
+ break;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
@@ -80386,6 +81365,31 @@
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
+ function hasInternalAnnotation(range, currentSourceFile) {
+ var comment = currentSourceFile.text.substring(range.pos, range.end);
+ return ts.stringContains(comment, "@internal");
+ }
+ function isInternalDeclaration(node, currentSourceFile) {
+ var parseTreeNode = ts.getParseTreeNode(node);
+ if (parseTreeNode && parseTreeNode.kind === 151 /* Parameter */) {
+ var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
+ var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
+ var text = currentSourceFile.text;
+ var commentRanges = previousSibling
+ ? ts.concatenate(
+ // to handle
+ // ... parameters, /* @internal */
+ // public param: string
+ ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
+ : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
+ return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
+ }
+ var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
+ return !!ts.forEach(leadingCommentRanges, function (range) {
+ return hasInternalAnnotation(range, currentSourceFile);
+ });
+ }
+ ts.isInternalDeclaration = isInternalDeclaration;
var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
2048 /* WriteClassExpressionAsTypeLiteral */ |
4096 /* UseTypeOfFunction */ |
@@ -80514,10 +81518,10 @@
}
}
function transformRoot(node) {
- if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
+ if (node.kind === 284 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
}
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
isBundledEmit = true;
refs = ts.createMap();
libs = ts.createMap();
@@ -80547,9 +81551,15 @@
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 === 282 /* InputFiles */) {
- return ts.createUnparsedSourceFile(prepend, "dts");
+ if (prepend.kind === 287 /* InputFiles */) {
+ var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
+ hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
+ collectReferences(sourceFile, refs);
+ recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
+ collectLibs(sourceFile, libs);
+ return sourceFile;
}
+ return prepend;
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -80641,7 +81651,7 @@
}
}
function collectReferences(sourceFile, ret) {
- if (noResolve || ts.isSourceFileJS(sourceFile))
+ if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
return ret;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
@@ -81188,7 +82198,9 @@
if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
return undefined;
}
+ getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker);
+ getSymbolAccessibilityDiagnostic = oldDiag;
var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
});
@@ -81231,7 +82243,7 @@
if (ctor) {
var oldDiag_1 = getSymbolAccessibilityDiagnostic;
parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
- if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */))
+ if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
return;
getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
if (param.name.kind === 72 /* Identifier */) {
@@ -81367,18 +82379,8 @@
}
errorNameNode = undefined;
}
- function hasInternalAnnotation(range) {
- var comment = currentSourceFile.text.substring(range.pos, range.end);
- return ts.stringContains(comment, "@internal");
- }
function shouldStripInternal(node) {
- if (stripInternal && node) {
- var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile);
- if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
- return true;
- }
- }
- return false;
+ return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
}
function isScopeMarker(node) {
return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
@@ -81400,7 +82402,7 @@
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 === 279 /* SourceFile */;
+ var parentIsFile = node.parent.kind === 284 /* SourceFile */;
if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */);
additions = 0 /* None */;
@@ -81569,9 +82571,15 @@
if (jsx === 2 /* React */) {
transformers.push(ts.transformJsx);
}
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
transformers.push(ts.transformESNext);
}
+ if (languageVersion < 6 /* ES2019 */) {
+ transformers.push(ts.transformES2019);
+ }
+ if (languageVersion < 5 /* ES2018 */) {
+ transformers.push(ts.transformES2018);
+ }
if (languageVersion < 4 /* ES2017 */) {
transformers.push(ts.transformES2017);
}
@@ -81611,7 +82619,7 @@
* @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(312 /* Count */);
+ var enabledSyntaxKindFeatures = new Array(317 /* Count */);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -81871,10 +82879,14 @@
})(ts || (ts = {}));
var ts;
(function (ts) {
- var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
var syntheticParent = { pos: -1, end: -1 };
/*@internal*/
+ function isBuildInfoFile(file) {
+ return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
+ }
+ ts.isBuildInfoFile = isBuildInfoFile;
+ /*@internal*/
/**
* Iterates over the source files that are expected to have an emit output.
*
@@ -81884,13 +82896,14 @@
* 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, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
+ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles, onlyBuildInfo, includeBuildInfo) {
if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; }
var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
+ var prepends = host.getPrependNodes();
+ if (sourceFiles.length || prepends.length) {
+ var bundle = ts.createBundle(sourceFiles, prepends);
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -81898,6 +82911,7 @@
}
}
else {
+ if (!onlyBuildInfo) {
for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
var sourceFile = sourceFiles_1[_a];
var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
@@ -81906,23 +82920,52 @@
}
}
}
+ if (includeBuildInfo) {
+ var buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
+ if (buildInfoPath)
+ return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
+ }
+ }
}
ts.forEachEmittedFile = forEachEmittedFile;
/*@internal*/
+ function getOutputPathForBuildInfo(options) {
+ var configFile = options.configFilePath;
+ if (!configFile || !ts.isIncrementalCompilation(options))
+ return undefined;
+ if (options.tsBuildInfoFile)
+ return options.tsBuildInfoFile;
+ var outPath = options.outFile || options.out;
+ var buildInfoExtensionLess;
+ if (outPath) {
+ buildInfoExtensionLess = ts.removeFileExtension(outPath);
+ }
+ else {
+ var configFileExtensionLess = ts.removeFileExtension(configFile);
+ buildInfoExtensionLess = options.outDir ?
+ options.rootDir ?
+ ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
+ ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
+ configFileExtensionLess;
+ }
+ return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
+ }
+ ts.getOutputPathForBuildInfo = getOutputPathForBuildInfo;
+ /*@internal*/
function getOutputPathsForBundle(options, forceDtsPaths) {
var outPath = options.outFile || options.out;
var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
var declarationMapPath = declarationFilePath && 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 };
+ var buildInfoPath = getOutputPathForBuildInfo(options);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
}
ts.getOutputPathsForBundle = getOutputPathsForBundle;
/*@internal*/
function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
var options = host.getCompilerOptions();
- if (sourceFile.kind === 280 /* Bundle */) {
+ if (sourceFile.kind === 285 /* Bundle */) {
return getOutputPathsForBundle(options, forceDtsPaths);
}
else {
@@ -81936,19 +82979,13 @@
var isJs = ts.isSourceFileJS(sourceFile);
var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
}
}
ts.getOutputPathsFor = getOutputPathsFor;
function getSourceMapFilePath(jsFilePath, options) {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
- function createDefaultBundleInfo() {
- return {
- originalOffset: -1,
- totalLength: -1
- };
- }
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
@@ -81971,9 +83008,91 @@
return ".js" /* Js */;
}
ts.getOutputExtension = getOutputExtension;
+ function rootDirOfOptions(configFile) {
+ return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.assertDefined(configFile.options.configFilePath));
+ }
+ function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
+ return outputDir ?
+ ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
+ inputFileName;
+ }
+ /* @internal */
+ function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
+ ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(inputFileName));
+ return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
+ }
+ ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
+ function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
+ var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
+ var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
+ ".json" /* Json */ :
+ ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
+ ".jsx" /* Jsx */ :
+ ".js" /* Js */);
+ return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.assertDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
+ outputFileName :
+ undefined;
+ }
+ /*@internal*/
+ function getAllProjectOutputs(configFile, ignoreCase) {
+ var outputs;
+ var addOutput = function (path) { return path && (outputs || (outputs = [])).push(path); };
+ if (configFile.options.outFile || configFile.options.out) {
+ var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ addOutput(jsFilePath);
+ addOutput(sourceMapFilePath);
+ addOutput(declarationFilePath);
+ addOutput(declarationMapPath);
+ addOutput(buildInfoPath);
+ }
+ else {
+ for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
+ var inputFileName = _c[_b];
+ if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
+ continue;
+ var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ addOutput(js);
+ if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
+ continue;
+ if (configFile.options.sourceMap) {
+ addOutput(js + ".map");
+ }
+ if (ts.getEmitDeclarations(configFile.options) && ts.hasTSFileExtension(inputFileName)) {
+ var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
+ addOutput(dts);
+ if (configFile.options.declarationMap) {
+ addOutput(dts + ".map");
+ }
+ }
+ }
+ addOutput(getOutputPathForBuildInfo(configFile.options));
+ }
+ return outputs || ts.emptyArray;
+ }
+ ts.getAllProjectOutputs = getAllProjectOutputs;
+ /*@internal*/
+ function getFirstProjectOutput(configFile, ignoreCase) {
+ if (configFile.options.outFile || configFile.options.out) {
+ var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
+ return ts.Debug.assertDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
+ }
+ for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
+ var inputFileName = _b[_a];
+ if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
+ continue;
+ var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ if (jsFilePath)
+ return jsFilePath;
+ }
+ var buildInfoPath = getOutputPathForBuildInfo(configFile.options);
+ if (buildInfoPath)
+ return buildInfoPath;
+ return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
+ }
+ ts.getFirstProjectOutput = getFirstProjectOutput;
/*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers, onlyBuildInfo) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -81981,12 +83100,12 @@
var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
var writer = ts.createTextWriter(newLine);
var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit;
- var bundleInfo = createDefaultBundleInfo();
+ var bundleBuildInfo;
var emitSkipped = false;
var exportedModulesFromDeclarationEmit;
// Emit each output file
enter();
- forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles);
+ forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile);
exit();
return {
emitSkipped: emitSkipped,
@@ -81996,9 +83115,16 @@
exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
+ bundleBuildInfo = {
+ commonSourceDirectory: host.getCommonSourceDirectory(),
+ sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return file.fileName; })
+ };
+ }
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
+ emitBuildInfo(bundleBuildInfo, buildInfoPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
if (jsFilePath) {
@@ -82007,8 +83133,8 @@
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
- if (bundleInfoPath) {
- emittedFilesList.push(bundleInfoPath);
+ if (buildInfoPath) {
+ emittedFilesList.push(buildInfoPath);
}
}
if (declarationFilePath) {
@@ -82019,8 +83145,21 @@
}
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
- if (emitOnlyDtsFiles || !jsFilePath) {
+ function emitBuildInfo(bundle, buildInfoPath) {
+ // Write build information if applicable
+ if (!buildInfoPath || targetSourceFile || emitSkipped)
+ return;
+ var program = host.getProgramBuildInfo();
+ if (!bundle && !program)
+ return;
+ if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
+ emitSkipped = true;
+ return;
+ }
+ ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: ts.version }), /*writeByteOrderMark*/ false);
+ }
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
+ if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
return;
}
// Make sure not to write js file and source map file if any of them cannot be written
@@ -82040,6 +83179,7 @@
inlineSourceMap: compilerOptions.inlineSourceMap,
inlineSources: compilerOptions.inlineSources,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ writeBundleFileInfo: !!bundleBuildInfo
};
// Create a printer to print the nodes
var printer = createPrinter(printerOptions, {
@@ -82050,12 +83190,14 @@
substituteNode: transform.substituteNode,
});
ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions);
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
// Clean up emit nodes on parse tree
transform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.js = printer.bundleFileInfo;
}
function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) {
- if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
+ if (!sourceFileOrBundle || !(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
return;
}
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
@@ -82084,6 +83226,8 @@
inlineSourceMap: compilerOptions.inlineSourceMap,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
onlyPrintJsDocStyle: true,
+ writeBundleFileInfo: !!bundleBuildInfo,
+ recordInternalSection: !!bundleBuildInfo
};
var declarationPrinter = createPrinter(printerOptions, {
// resolver hooks
@@ -82096,18 +83240,20 @@
emitSkipped = emitSkipped || declBlocked;
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, {
+ printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
sourceMap: compilerOptions.declarationMap,
sourceRoot: compilerOptions.sourceRoot,
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
- if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) {
+ if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 284 /* SourceFile */) {
var sourceFile = declarationTransform.transformed[0];
exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
}
}
declarationTransform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
}
function collectLinkedAliases(node) {
if (ts.isExportAssignment(node)) {
@@ -82122,16 +83268,16 @@
}
ts.forEachChild(node, collectLinkedAliases);
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) {
- var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined;
- var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined;
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
+ var bundle = sourceFileOrBundle.kind === 285 /* Bundle */ ? sourceFileOrBundle : undefined;
+ var sourceFile = sourceFileOrBundle.kind === 284 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
var sourceMapGenerator;
if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
}
if (bundle) {
- printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator);
+ printer.writeBundle(bundle, writer, sourceMapGenerator);
}
else {
printer.writeFile(sourceFile, writer, sourceMapGenerator);
@@ -82160,18 +83306,12 @@
}
// Write the output file
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
- // Write bundled offset information if applicable
- if (bundleInfoPath) {
- bundleInfo.totalLength = writer.getTextPos();
- ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false);
- }
// Reset state
writer.clear();
- bundleInfo = createDefaultBundleInfo();
}
function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
- && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
+ && (sourceFileOrBundle.kind !== 284 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
}
function getSourceRoot(mapOptions) {
// Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
@@ -82228,6 +83368,167 @@
}
}
ts.emitFiles = emitFiles;
+ /*@internal*/
+ function getBuildInfoText(buildInfo) {
+ return JSON.stringify(buildInfo, undefined, 2);
+ }
+ ts.getBuildInfoText = getBuildInfoText;
+ /*@internal*/
+ function getBuildInfo(buildInfoText) {
+ return JSON.parse(buildInfoText);
+ }
+ ts.getBuildInfo = getBuildInfo;
+ /*@internal*/
+ ts.notImplementedResolver = {
+ hasGlobalName: ts.notImplemented,
+ getReferencedExportContainer: ts.notImplemented,
+ getReferencedImportDeclaration: ts.notImplemented,
+ getReferencedDeclarationWithCollidingName: ts.notImplemented,
+ isDeclarationWithCollidingName: ts.notImplemented,
+ isValueAliasDeclaration: ts.notImplemented,
+ isReferencedAliasDeclaration: ts.notImplemented,
+ isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
+ getNodeCheckFlags: ts.notImplemented,
+ isDeclarationVisible: ts.notImplemented,
+ isLateBound: function (_node) { return false; },
+ collectLinkedAliases: ts.notImplemented,
+ isImplementationOfOverload: ts.notImplemented,
+ isRequiredInitializedParameter: ts.notImplemented,
+ isOptionalUninitializedParameterProperty: ts.notImplemented,
+ isExpandoFunctionDeclaration: ts.notImplemented,
+ getPropertiesOfContainerFunction: ts.notImplemented,
+ createTypeOfDeclaration: ts.notImplemented,
+ createReturnTypeOfSignatureDeclaration: ts.notImplemented,
+ createTypeOfExpression: ts.notImplemented,
+ createLiteralConstValue: ts.notImplemented,
+ isSymbolAccessible: ts.notImplemented,
+ isEntityNameVisible: ts.notImplemented,
+ // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
+ getConstantValue: ts.notImplemented,
+ getReferencedValueDeclaration: ts.notImplemented,
+ getTypeReferenceSerializationKind: ts.notImplemented,
+ isOptionalParameter: ts.notImplemented,
+ moduleExportsSomeValue: ts.notImplemented,
+ isArgumentsLocalBinding: ts.notImplemented,
+ getExternalModuleFileFromDeclaration: ts.notImplemented,
+ getTypeReferenceDirectivesForEntityName: ts.notImplemented,
+ getTypeReferenceDirectivesForSymbol: ts.notImplemented,
+ isLiteralConstDeclaration: ts.notImplemented,
+ getJsxFactoryEntity: ts.notImplemented,
+ getAllAccessorDeclarations: ts.notImplemented,
+ getSymbolOfExternalModuleSpecifier: ts.notImplemented,
+ isBindingCapturedByNode: ts.notImplemented,
+ };
+ function createSourceFilesFromBundleBuildInfo(bundle) {
+ var sourceFiles = bundle.sourceFiles.map(function (fileName) {
+ var sourceFile = ts.createNode(284 /* SourceFile */, 0, 0);
+ sourceFile.fileName = fileName;
+ sourceFile.text = "";
+ sourceFile.statements = ts.createNodeArray();
+ return sourceFile;
+ });
+ var jsBundle = ts.Debug.assertDefined(bundle.js);
+ ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
+ var sourceFile = sourceFiles[prologueInfo.file];
+ sourceFile.text = prologueInfo.text;
+ sourceFile.end = prologueInfo.text.length;
+ sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
+ var statement = ts.createNode(221 /* ExpressionStatement */, directive.pos, directive.end);
+ statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
+ statement.expression.text = directive.expression.text;
+ return statement;
+ }));
+ });
+ return sourceFiles;
+ }
+ /*@internal*/
+ function emitUsingBuildInfo(config, host, getCommandLine) {
+ var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
+ var buildInfoText = host.readFile(ts.Debug.assertDefined(buildInfoPath));
+ if (!buildInfoText)
+ return buildInfoPath;
+ var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath));
+ if (!jsFileText)
+ return jsFilePath;
+ var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
+ // error if no source map or for now if inline sourcemap
+ if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
+ return sourceMapFilePath || "inline sourcemap decoding";
+ // read declaration text
+ var declarationText = declarationFilePath && host.readFile(declarationFilePath);
+ if (declarationFilePath && !declarationText)
+ return declarationFilePath;
+ var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
+ // error if no source map or for now if inline sourcemap
+ if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
+ return declarationMapPath || "inline sourcemap decoding";
+ var buildInfo = getBuildInfo(buildInfoText);
+ if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
+ return buildInfoPath;
+ var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo,
+ /*onlyOwnText*/ true);
+ var outputFiles = [];
+ var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
+ var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle);
+ var emitHost = {
+ getPrependNodes: ts.memoize(function () { return prependNodes.concat([ownPrependInput]); }),
+ getCanonicalFileName: host.getCanonicalFileName,
+ getCommonSourceDirectory: function () { return buildInfo.bundle.commonSourceDirectory; },
+ getCompilerOptions: function () { return config.options; },
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ getNewLine: function () { return host.getNewLine(); },
+ getSourceFile: ts.returnUndefined,
+ getSourceFileByPath: ts.returnUndefined,
+ getSourceFiles: function () { return sourceFilesForJsEmit; },
+ getLibFileFromReference: ts.notImplemented,
+ isSourceFileFromExternalLibrary: ts.returnFalse,
+ getResolvedProjectReferenceToRedirect: ts.returnUndefined,
+ writeFile: function (name, text, writeByteOrderMark) {
+ switch (name) {
+ case jsFilePath:
+ if (jsFileText === text)
+ return;
+ break;
+ case sourceMapFilePath:
+ if (sourceMapText === text)
+ return;
+ break;
+ case buildInfoPath:
+ var newBuildInfo = getBuildInfo(text);
+ newBuildInfo.program = buildInfo.program;
+ // Update sourceFileInfo
+ var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
+ newBuildInfo.bundle.js.sources = js.sources;
+ if (dts) {
+ newBuildInfo.bundle.dts.sources = dts.sources;
+ }
+ newBuildInfo.bundle.sourceFiles = sourceFiles;
+ outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
+ return;
+ case declarationFilePath:
+ if (declarationText === text)
+ return;
+ break;
+ case declarationMapPath:
+ if (declarationMapText === text)
+ return;
+ break;
+ default:
+ ts.Debug.fail("Unexpected path: " + name);
+ }
+ outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
+ },
+ isEmitBlocked: ts.returnFalse,
+ readFile: function (f) { return host.readFile(f); },
+ fileExists: function (f) { return host.fileExists(f); },
+ directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }),
+ useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
+ getProgramBuildInfo: ts.returnUndefined
+ };
+ emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, /*emitOnlyDtsFiles*/ false, ts.getTransformers(config.options));
+ return outputFiles;
+ }
+ ts.emitUsingBuildInfo = emitUsingBuildInfo;
var PipelinePhase;
(function (PipelinePhase) {
PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
@@ -82256,6 +83557,10 @@
var ownWriter; // Reusable `EmitTextWriter` for basic printing.
var write = writeBase;
var isOwnFileEmit;
+ var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
+ var recordInternalSection = printerOptions.recordInternalSection;
+ var sourceFileTextPos = 0;
+ var sourceFileTextKind = "text" /* Text */;
// Source Maps
var sourceMapsDisabled = true;
var sourceMapGenerator;
@@ -82281,7 +83586,8 @@
writeNode: writeNode,
writeList: writeList,
writeFile: writeFile,
- writeBundle: writeBundle
+ writeBundle: writeBundle,
+ bundleFileInfo: bundleFileInfo
};
function printNode(hint, node, sourceFile) {
switch (hint) {
@@ -82296,9 +83602,9 @@
break;
}
switch (node.kind) {
- case 279 /* SourceFile */: return printFile(node);
- case 280 /* Bundle */: return printBundle(node);
- case 281 /* UnparsedSource */: return printUnparsedSource(node);
+ case 284 /* SourceFile */: return printFile(node);
+ case 285 /* Bundle */: return printBundle(node);
+ case 286 /* UnparsedSource */: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -82308,7 +83614,7 @@
return endPrint();
}
function printBundle(bundle) {
- writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined);
+ writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
return endPrint();
}
function printFile(sourceFile) {
@@ -82336,7 +83642,49 @@
reset();
writer = previousWriter;
}
- function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) {
+ function getTextPosWithWriteLine() {
+ return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
+ }
+ function updateOrPushBundleFileTextLike(pos, end, kind) {
+ var last = ts.lastOrUndefined(bundleFileInfo.sections);
+ if (last && last.kind === kind) {
+ last.end = end;
+ }
+ else {
+ bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
+ }
+ }
+ function recordBundleFileInternalSectionStart(node) {
+ if (recordInternalSection &&
+ bundleFileInfo &&
+ currentSourceFile &&
+ (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
+ ts.isInternalDeclaration(node, currentSourceFile) &&
+ sourceFileTextKind !== "internal" /* Internal */) {
+ var prevSourceFileTextKind = sourceFileTextKind;
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = "internal" /* Internal */;
+ return prevSourceFileTextKind;
+ }
+ return undefined;
+ }
+ function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
+ if (prevSourceFileTextKind) {
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = prevSourceFileTextKind;
+ }
+ }
+ function recordBundleFileTextLikeSection(end) {
+ if (sourceFileTextPos < end) {
+ updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
+ return true;
+ }
+ return false;
+ }
+ function writeBundle(bundle, output, sourceMapGenerator) {
+ var _a;
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output, sourceMapGenerator);
@@ -82344,18 +83692,49 @@
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
- var prepend = _b[_a];
+ for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
+ var prepend = _c[_b];
writeLine();
+ var pos = writer.getTextPos();
+ var savedSections = bundleFileInfo && bundleFileInfo.sections;
+ if (savedSections)
+ bundleFileInfo.sections = [];
print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
+ if (bundleFileInfo) {
+ var newSections = bundleFileInfo.sections;
+ bundleFileInfo.sections = savedSections;
+ if (prepend.oldFileOfCurrentEmit)
+ (_a = bundleFileInfo.sections).push.apply(_a, newSections);
+ else {
+ newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prepend" /* Prepend */, data: prepend.fileName, texts: newSections });
}
- if (bundleInfo) {
- bundleInfo.originalOffset = writer.getTextPos();
}
- for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
- var sourceFile = _d[_c];
+ }
+ sourceFileTextPos = getTextPosWithWriteLine();
+ for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
+ var sourceFile = _e[_d];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
+ if (bundleFileInfo && bundle.sourceFiles.length) {
+ var end = writer.getTextPos();
+ if (recordBundleFileTextLikeSection(end)) {
+ // Store prologues
+ var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
+ if (prologues) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.prologues = prologues;
+ }
+ // Store helpes
+ var helpers = getHelpersFromBundledSourceFiles(bundle);
+ if (helpers) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.helpers = helpers;
+ }
+ }
+ }
reset();
writer = previousWriter;
}
@@ -82425,8 +83804,10 @@
function emit(node) {
if (node === undefined)
return;
+ var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
pipelinePhase(4 /* Unspecified */, node);
+ recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
}
function emitIdentifierName(node) {
if (node === undefined)
@@ -82453,12 +83834,12 @@
}
// falls through
case 2 /* Comments */:
- if (!commentsDisabled && node.kind !== 279 /* SourceFile */) {
+ if (!commentsDisabled && node.kind !== 284 /* SourceFile */) {
return pipelineEmitWithComments;
}
// falls through
case 3 /* SourceMaps */:
- if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) {
+ if (!sourceMapsDisabled && node.kind !== 284 /* SourceFile */ && !ts.isInJsonFile(node)) {
return pipelineEmitWithSourceMap;
}
// falls through
@@ -82495,8 +83876,16 @@
case 16 /* TemplateMiddle */:
case 17 /* TemplateTail */:
return emitLiteral(node);
- case 281 /* UnparsedSource */:
- return emitUnparsedSource(node);
+ case 286 /* UnparsedSource */:
+ case 280 /* UnparsedPrepend */:
+ return emitUnparsedSourceOrPrepend(node);
+ case 279 /* UnparsedPrologue */:
+ return writeUnparsedNode(node);
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return emitUnparsedTextLike(node);
+ case 283 /* UnparsedSyntheticReference */:
+ return emitUnparsedSyntheticReference(node);
// Identifiers
case 72 /* Identifier */:
return emitIdentifier(node);
@@ -82540,7 +83929,7 @@
return emitTypeReference(node);
case 165 /* FunctionType */:
return emitFunctionType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return emitJSDocFunctionType(node);
case 166 /* ConstructorType */:
return emitConstructorType(node);
@@ -82578,20 +83967,20 @@
return emitLiteralType(node);
case 183 /* ImportType */:
return emitImportTypeNode(node);
- case 284 /* JSDocAllType */:
+ case 289 /* JSDocAllType */:
writePunctuation("*");
return;
- case 285 /* JSDocUnknownType */:
+ case 290 /* JSDocUnknownType */:
writePunctuation("?");
return;
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return emitJSDocNullableType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return emitJSDocNonNullableType(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return emitJSDocOptionalType(node);
case 172 /* RestType */:
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return emitRestOrJSDocVariadicType(node);
// Binding patterns
case 184 /* ObjectBindingPattern */:
@@ -82729,30 +84118,30 @@
case 278 /* EnumMember */:
return emitEnumMember(node);
// JSDoc nodes (only used in codefixes currently)
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return emitJSDocPropertyLikeTag(node);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return emitJSDocSimpleTypedTag(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return emitJSDocAugmentsTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return emitJSDocTemplateTag(node);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return emitJSDocTypedefTag(node);
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return emitJSDocCallbackTag(node);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return emitJSDocSignature(node);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return emitJSDocTypeLiteral(node);
- case 296 /* JSDocClassTag */:
- case 294 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
return emitJSDocSimpleTag(node);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return emitJSDoc(node);
// Transformation nodes (ignored)
}
@@ -82851,9 +84240,9 @@
case 264 /* JsxFragment */:
return emitJsxFragment(node);
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return emitPartiallyEmittedExpression(node);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return emitCommaList(node);
}
}
@@ -82869,22 +84258,45 @@
var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node);
pipelinePhase(hint, substituteNode(hint, node));
}
+ function getHelpersFromBundledSourceFiles(bundle) {
+ var result;
+ if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
+ return undefined;
+ }
+ var bundledHelpers = ts.createMap();
+ for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
+ var helpers = getSortedEmitHelpers(sourceFile);
+ if (!helpers)
+ continue;
+ for (var _c = 0, helpers_3 = helpers; _c < helpers_3.length; _c++) {
+ var helper = helpers_3[_c];
+ if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
+ bundledHelpers.set(helper.name, true);
+ (result || (result = [])).push(helper.name);
+ }
+ }
+ }
+ return result;
+ }
function emitHelpers(node) {
var helpersEmitted = false;
- var bundle = node.kind === 280 /* Bundle */ ? node : undefined;
+ var bundle = node.kind === 285 /* Bundle */ ? node : undefined;
if (bundle && moduleKind === ts.ModuleKind.None) {
return;
}
- var numNodes = bundle ? bundle.sourceFiles.length : 1;
+ var numPrepends = bundle ? bundle.prepends.length : 0;
+ var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
for (var i = 0; i < numNodes; i++) {
- var currentNode = bundle ? bundle.sourceFiles[i] : node;
- var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile;
- var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined;
- var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit;
- var helpers = ts.getEmitHelpers(currentNode);
+ var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
+ var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
+ var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
+ var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
+ var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
if (helpers) {
- for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
- var helper = _b[_a];
+ for (var _a = 0, helpers_4 = helpers; _a < helpers_4.length; _a++) {
+ var helper = helpers_4[_a];
if (!helper.scoped) {
// Skip the helper if it can be skipped and the noEmitHelpers compiler
// option is set, or if it can be imported and the importHelpers compiler
@@ -82904,18 +84316,25 @@
// Skip the helper if it is scoped and we are emitting bundled helpers
continue;
}
+ var pos = getTextPosWithWriteLine();
if (typeof helper.text === "string") {
writeLines(helper.text);
}
else {
writeLines(helper.text(makeFileLevelOptimisticUniqueName));
}
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
helpersEmitted = true;
}
}
}
return helpersEmitted;
}
+ function getSortedEmitHelpers(node) {
+ var helpers = ts.getEmitHelpers(node);
+ return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
+ }
//
// Literals/Pseudo-literals
//
@@ -82942,8 +84361,42 @@
}
}
// SyntaxKind.UnparsedSource
- function emitUnparsedSource(unparsed) {
- writer.rawWrite(unparsed.text);
+ // SyntaxKind.UnparsedPrepend
+ function emitUnparsedSourceOrPrepend(unparsed) {
+ for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
+ var text = _b[_a];
+ writeLine();
+ emit(text);
+ }
+ }
+ // SyntaxKind.UnparsedPrologue
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ // SyntaxKind.UnparsedSyntheticReference
+ function writeUnparsedNode(unparsed) {
+ writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
+ }
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ function emitUnparsedTextLike(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 281 /* UnparsedText */ ?
+ "text" /* Text */ :
+ "internal" /* Internal */);
+ }
+ }
+ // SyntaxKind.UnparsedSyntheticReference
+ function emitUnparsedSyntheticReference(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ var section = ts.clone(unparsed.section);
+ section.pos = pos;
+ section.end = writer.getTextPos();
+ bundleFileInfo.sections.push(section);
+ }
}
//
// Identifiers
@@ -82998,7 +84451,7 @@
emit(node.dotDotDotToken);
emitNodeWithWriter(node.name, writeParameter);
emit(node.questionToken);
- if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) {
+ if (node.parent && node.parent.kind === 294 /* JSDocFunctionType */ && !node.name) {
emit(node.type);
}
else {
@@ -83878,7 +85331,7 @@
}
function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
// Emit all the prologue directives (like "use strict").
- var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true);
+ var statementOffset = emitPrologueDirectives(body.statements);
var pos = writer.getTextPos();
emitHelpers(body);
if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
@@ -84138,7 +85591,7 @@
writePunctuation(">");
}
function emitJsxText(node) {
- writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true));
+ writer.writeLiteral(node.text);
}
function emitJsxClosingElementOrFragment(node) {
writePunctuation("</");
@@ -84283,7 +85736,7 @@
}
}
if (node.tags) {
- if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) {
+ if (node.tags.length === 1 && node.tags[0].kind === 307 /* JSDocTypeTag */ && !node.comment) {
writeSpace();
emit(node.tags[0]);
}
@@ -84317,7 +85770,7 @@
function emitJSDocTypedefTag(tag) {
emitJSDocTagName(tag.tagName);
if (tag.typeExpression) {
- if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
emitJSDocTypeExpression(tag.typeExpression);
}
else {
@@ -84336,7 +85789,7 @@
emit(tag.fullName);
}
emitJSDocComment(tag.comment);
- if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) {
+ if (tag.typeExpression && tag.typeExpression.kind === 297 /* JSDocTypeLiteral */) {
emitJSDocTypeLiteral(tag.typeExpression);
}
}
@@ -84423,6 +85876,16 @@
}
function emitSyntheticTripleSlashReferencesIfNeeded(node) {
emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
+ for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
+ for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
+ var ref = _d[_c];
+ emit(ref);
+ writeLine();
+ }
+ }
+ }
}
function emitTripleSlashDirectivesIfNeeded(node) {
if (node.isDeclarationFile)
@@ -84430,7 +85893,10 @@
}
function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
if (hasNoDefaultLib) {
+ var pos = writer.getTextPos();
writeComment("/// <reference no-default-lib=\"true\"/>");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
writeLine();
}
if (currentSourceFile && currentSourceFile.moduleName) {
@@ -84451,17 +85917,26 @@
}
for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
var directive = files_1[_c];
+ var pos = writer.getTextPos();
writeComment("/// <reference path=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
writeLine();
}
- for (var _d = 0, types_18 = types; _d < types_18.length; _d++) {
- var directive = types_18[_d];
+ for (var _d = 0, types_19 = types; _d < types_19.length; _d++) {
+ var directive = types_19[_d];
+ var pos = writer.getTextPos();
writeComment("/// <reference types=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
writeLine();
}
for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
var directive = libs_1[_e];
+ var pos = writer.getTextPos();
writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
writeLine();
}
}
@@ -84486,16 +85961,22 @@
* Emits any prologue directives at the start of a Statement list, returning the
* number of prologue directives written to the output.
*/
- function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) {
+ function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
+ var needsToSetSourceFile = !!sourceFile;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (ts.isPrologueDirective(statement)) {
var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
if (shouldEmitPrologueDirective) {
- if (startWithNewLine || i > 0) {
- writeLine();
+ if (needsToSetSourceFile) {
+ needsToSetSourceFile = false;
+ setSourceFile(sourceFile);
}
+ writeLine();
+ var pos = writer.getTextPos();
emit(statement);
+ if (recordBundleFileSection && bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
if (seenPrologueDirectives) {
seenPrologueDirectives.set(statement.expression.text, true);
}
@@ -84508,23 +85989,70 @@
}
return statements.length;
}
+ function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
+ for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
+ var prologue = prologues_1[_a];
+ if (!seenPrologueDirectives.has(prologue.data)) {
+ writeLine();
+ var pos = writer.getTextPos();
+ emit(prologue);
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
+ if (seenPrologueDirectives) {
+ seenPrologueDirectives.set(prologue.data, true);
+ }
+ }
+ }
+ }
function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
if (ts.isSourceFile(sourceFileOrBundle)) {
- setSourceFile(sourceFileOrBundle);
- emitPrologueDirectives(sourceFileOrBundle.statements);
+ emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
}
else {
var seenPrologueDirectives = ts.createMap();
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
- setSourceFile(sourceFile);
- emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
+ emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
}
setSourceFile(undefined);
}
}
+ function getPrologueDirectivesFromBundledSourceFiles(bundle) {
+ var seenPrologueDirectives = ts.createMap();
+ var prologues;
+ for (var index = 0; index < bundle.sourceFiles.length; index++) {
+ var sourceFile = bundle.sourceFiles[index];
+ var directives = void 0;
+ var end = 0;
+ for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
+ var statement = _b[_a];
+ if (!ts.isPrologueDirective(statement))
+ break;
+ if (seenPrologueDirectives.has(statement.expression.text))
+ continue;
+ seenPrologueDirectives.set(statement.expression.text, true);
+ (directives || (directives = [])).push({
+ pos: statement.pos,
+ end: statement.end,
+ expression: {
+ pos: statement.expression.pos,
+ end: statement.expression.end,
+ text: statement.expression.text
+ }
+ });
+ end = end < statement.end ? statement.end : end;
+ }
+ if (directives)
+ (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
+ }
+ return prologues;
+ }
function emitShebangIfNeeded(sourceFileOrBundle) {
- if (ts.isSourceFile(sourceFileOrBundle)) {
+ if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
var shebang = ts.getShebang(sourceFileOrBundle.text);
if (shebang) {
writeComment(shebang);
@@ -84533,11 +86061,18 @@
}
}
else {
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ ts.Debug.assertNode(prepend, ts.isUnparsedSource);
+ if (emitShebangIfNeeded(prepend)) {
+ return true;
+ }
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
// Emit only the first encountered shebang
if (emitShebangIfNeeded(sourceFile)) {
- break;
+ return true;
}
}
}
@@ -84740,6 +86275,7 @@
}
// Emit each child.
var previousSibling = void 0;
+ var previousSourceFileTextKind = void 0;
var shouldDecreaseIndentAfterEmit = false;
for (var i = 0; i < count; i++) {
var child = children[start + i];
@@ -84760,6 +86296,7 @@
emitLeadingCommentsOfPosition(previousSibling.end);
}
writeDelimiter(format);
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write either a line terminator or whitespace to separate the elements.
if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
// If a synthesized node in a single-line list starts on a new
@@ -84776,6 +86313,7 @@
}
}
// Emit this child.
+ previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
if (shouldEmitInterveningComments) {
if (emitTrailingCommentsOfPosition) {
var commentRange = ts.getCommentRange(child);
@@ -84810,6 +86348,7 @@
if (format & 128 /* Indented */) {
decreaseIndent();
}
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write the closing line terminator or closing whitespace.
if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
writeLine();
@@ -84911,7 +86450,6 @@
if (line.length) {
writeLine();
write(line);
- writer.rawWrite(newLine);
}
}
}
@@ -85425,7 +86963,7 @@
hasWrittenComment = false;
var emitFlags = ts.getEmitFlags(node);
var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
- var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 312 /* 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 === 11 /* JsxText */;
@@ -85685,19 +87223,28 @@
return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
}
// Source Maps
+ function getParsedSourceMap(node) {
+ if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
+ node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
+ }
+ return node.parsedSourceMap || undefined;
+ }
function pipelineEmitWithSourceMap(hint, node) {
var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node);
- if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) {
- var parsed = ts.tryParseRawSourceMap(node.sourceMapText);
- if (parsed) {
- sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath);
+ if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
+ pipelinePhase(hint, node);
+ }
+ else if (ts.isUnparsedNode(node)) {
+ var parsed = getParsedSourceMap(node.parent);
+ if (parsed && sourceMapGenerator) {
+ sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
}
pipelinePhase(hint, node);
}
else {
var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
var emitFlags = ts.getEmitFlags(node);
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitSourcePos(source, skipSourceTrivia(source, pos));
@@ -85710,7 +87257,7 @@
else {
pipelinePhase(hint, node);
}
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitSourcePos(source, end);
@@ -85838,7 +87385,8 @@
writeFile: host.writeFile && writeFile,
addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
addOrDeleteFile: addOrDeleteFile,
- clearCache: clearCache
+ clearCache: clearCache,
+ realpath: host.realpath && realpath
};
function toPath(fileName) {
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
@@ -85935,7 +87483,7 @@
var rootDirPath = toPath(rootDir);
var result = tryReadDirectory(rootDir, rootDirPath);
if (result) {
- return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries);
+ return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
}
return host.readDirectory(rootDir, extensions, excludes, includes, depth);
function getFileSystemEntries(dir) {
@@ -85946,6 +87494,9 @@
return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
}
}
+ function realpath(s) {
+ return host.realpath ? host.realpath(s) : s;
+ }
function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
if (existingResult) {
@@ -86216,11 +87767,7 @@
function createCompilerHostWorker(options, setParentNodes, system) {
if (system === void 0) { system = ts.sys; }
var existingDirectories = ts.createMap();
- function getCanonicalFileName(fileName) {
- // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
- // otherwise use toLowerCase as a canonical form.
- return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
- }
+ var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
function getSourceFile(fileName, languageVersion, onError) {
var text;
try {
@@ -86345,20 +87892,21 @@
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
- return value || undefined;
+ return value !== false ? value : undefined;
return setReadFileCache(key, fileName);
};
var setReadFileCache = function (key, fileName) {
var newValue = originalReadFile.call(host, fileName);
- readFileCache.set(key, newValue || false);
+ readFileCache.set(key, newValue !== undefined ? newValue : false);
return newValue;
};
host.readFile = function (fileName) {
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
- return value; // could be .d.ts from output
- if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ return value !== false ? value : undefined; // could be .d.ts from output
+ // Cache json or buildInfo
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
return originalReadFile.call(host, fileName);
}
return setReadFileCache(key, fileName);
@@ -86389,7 +87937,7 @@
var key = toPath(fileName);
fileExistsCache.delete(key);
var value = readFileCache.get(key);
- if (value && value !== data) {
+ if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.delete(key);
}
@@ -86835,11 +88383,18 @@
if (rootNames.length) {
for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
var parsedRef = resolvedProjectReferences_1[_i];
- if (parsedRef) {
+ if (!parsedRef)
+ continue;
var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
if (out) {
- var dtsOutfile = ts.changeExtension(out, ".d.ts");
- processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ }
+ else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
+ for (var _a = 0, _b = parsedRef.commandLine.fileNames; _a < _b.length; _a++) {
+ var fileName = _b[_a];
+ if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(fileName)) {
+ processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ }
}
}
}
@@ -86887,8 +88442,8 @@
// not part of the new program.
if (oldProgram && host.onReleaseOldSourceFile) {
var oldSourceFiles = oldProgram.getSourceFiles();
- for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) {
- var oldSourceFile = oldSourceFiles_1[_a];
+ for (var _c = 0, oldSourceFiles_1 = oldSourceFiles; _c < oldSourceFiles_1.length; _c++) {
+ var oldSourceFile = oldSourceFiles_1[_c];
var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
if (shouldCreateNewSourceFile || !newFile ||
// old file wasnt redirect but new file is
@@ -86944,7 +88499,8 @@
getProjectReferenceRedirect: getProjectReferenceRedirect,
getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
- forEachResolvedProjectReference: forEachResolvedProjectReference
+ forEachResolvedProjectReference: forEachResolvedProjectReference,
+ emitBuildInfo: emitBuildInfo
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -86973,7 +88529,7 @@
}
function getCommonSourceDirectory() {
if (commonSourceDirectory === undefined) {
- var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); });
+ var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
// If a rootDir is specified use it as the commonSourceDirectory
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
@@ -87362,7 +88918,8 @@
}
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, getLibFileFromReference: program.getLibFileFromReference, 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) {
+ 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, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
+ getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, 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))
@@ -87371,7 +88928,20 @@
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(); } });
+ } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); } });
+ }
+ function emitBuildInfo(writeFileCallback) {
+ ts.Debug.assert(!options.out && !options.outFile);
+ ts.performance.mark("beforeEmit");
+ var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback),
+ /*targetSourceFile*/ undefined,
+ /*emitOnlyDtsFiles*/ false,
+ /*transformers*/ undefined,
+ /*declaraitonTransformers*/ undefined,
+ /*onlyBuildInfo*/ true);
+ ts.performance.mark("afterEmit");
+ ts.performance.measure("Emit", "beforeEmit", "afterEmit");
+ return emitResult;
}
function getResolvedProjectReferences() {
return resolvedProjectReferences;
@@ -87380,28 +88950,11 @@
return projectReferences;
}
function getPrependNodes() {
- if (!projectReferences) {
- return ts.emptyArray;
- }
- var nodes = [];
- for (var i = 0; i < projectReferences.length; i++) {
- var ref = projectReferences[i];
- var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
- if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
- var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
- // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
- if (!out)
- continue;
- var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- var node = ts.createInputFiles(function (fileName) {
+ return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
var path = toPath(fileName);
var sourceFile = getSourceFileByPath(path);
return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
- }, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath);
- nodes.push(node);
- }
- }
- return nodes;
+ });
}
function isSourceFileFromExternalLibrary(file) {
return !!sourceFilesFoundSearchingNodeModules.get(file.path);
@@ -87473,8 +89026,7 @@
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
ts.performance.mark("beforeEmit");
var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217
- emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -88086,7 +89638,6 @@
if (refFile) {
var redirect = getProjectReferenceRedirect(fileName);
if (redirect) {
- (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName);
fileName = redirect;
// Once we start redirecting to a file, we can potentially come back to it
// via a back-reference from another file in the .d.ts folder. If that happens we'll
@@ -88183,7 +89734,7 @@
var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
return out ?
ts.changeExtension(out, ".d.ts" /* Dts */) :
- ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine);
+ ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
}
/**
* Get the referenced project if the file is input file from that reference project
@@ -88476,18 +90027,29 @@
if (options.declaration === false) {
createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
}
+ if (options.incremental === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
+ }
+ }
+ if (options.tsBuildInfoFile) {
+ if (!ts.isIncrementalCompilation(options)) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
+ }
}
verifyProjectReferences();
// List of collected files is complete; validate exhautiveness if this is a project with a file list
if (options.composite) {
- var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; });
- if (rootNames.length < sourceFiles.length) {
- var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); });
- for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) {
- var file = _a[_i];
- if (normalizedRootNames.indexOf(file) === -1) {
- 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));
- }
+ var rootPaths = rootNames.map(toPath);
+ for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
+ var file = files_3[_i];
+ // Ignore declaration files
+ if (file.isDeclarationFile)
+ continue;
+ // Ignore json file thats from project reference
+ if (ts.isJsonSourceFile(file) && getResolvedProjectReferenceToRedirect(file.fileName))
+ continue;
+ if (rootPaths.indexOf(file.path) === -1) {
+ 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.fileName));
}
}
}
@@ -88670,6 +90232,7 @@
}
}
function verifyProjectReferences() {
+ var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getOutputPathForBuildInfo(options) : undefined;
forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
var parentFile = parent && parent.sourceFile;
@@ -88696,6 +90259,10 @@
createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
}
}
+ if (!parent && buildInfoPath && buildInfoPath === ts.getOutputPathForBuildInfo(options)) {
+ createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
+ hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
+ }
});
}
function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
@@ -88840,11 +90407,32 @@
readFile: function (f) { return directoryStructureHost.readFile(f); },
useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
getCurrentDirectory: function () { return host.getCurrentDirectory(); },
- onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || (function () { return undefined; }),
+ onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
trace: host.trace ? function (s) { return host.trace(s); } : undefined
};
}
ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
+ /* @internal */
+ function createPrependNodes(projectReferences, getCommandLine, readFile) {
+ if (!projectReferences)
+ return ts.emptyArray;
+ var nodes;
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = getCommandLine(ref, i);
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!out)
+ continue;
+ var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
+ (nodes || (nodes = [])).push(node);
+ }
+ }
+ return nodes || ts.emptyArray;
+ }
+ ts.createPrependNodes = createPrependNodes;
function resolveProjectReferencePath(hostOrRef, ref) {
var passedInRef = ref ? ref : hostOrRef;
return ts.resolveConfigFileProjectName(passedInRef.path);
@@ -89041,7 +90629,7 @@
// Create the reference map, and set the file infos
for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
- var version_1 = sourceFile.version;
+ var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined;
if (referencedMap) {
var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
@@ -89096,9 +90684,9 @@
*/
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
+ // They will be committed once it is safe to use them
// eg when calling this api from tsserver, if there is no cancellation of the operation
- // In the other cases the affected files signatures are commited only after the iteration through the result is complete
+ // In the other cases the affected files signatures are committed only after the iteration through the result is complete
var signatureCache = cacheToUpdateSignature || ts.createMap();
var sourceFile = programOfThisState.getSourceFileByPath(path);
if (!sourceFile) {
@@ -89388,11 +90976,14 @@
var affectedSignatures = oldState.currentAffectedFilesSignatures;
ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
}
+ var changedFilesSet = oldState.changedFilesSet;
if (canCopySemanticDiagnostics) {
- ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
+ ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
}
// Copy old state's changed files set
- ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet);
+ if (changedFilesSet) {
+ ts.copyEntries(changedFilesSet, state.changedFilesSet);
+ }
if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit;
state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
@@ -89430,7 +91021,7 @@
// Unchanged file copy diagnostics
var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
if (diagnostics) {
- state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics);
+ state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics);
if (!state.semanticDiagnosticsFromOldState) {
state.semanticDiagnosticsFromOldState = ts.createMap();
}
@@ -89438,8 +91029,45 @@
}
}
});
+ if (oldCompilerOptions &&
+ (oldCompilerOptions.outDir !== compilerOptions.outDir ||
+ oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
+ (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
+ // Add all files to affectedFilesPendingEmit since emit changed
+ state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(function (f) { return f.path; }));
+ if (state.affectedFilesPendingEmitIndex === undefined) {
+ state.affectedFilesPendingEmitIndex = 0;
+ }
+ ts.Debug.assert(state.seenAffectedFiles === undefined);
+ state.seenAffectedFiles = ts.createMap();
+ }
return state;
}
+ function convertToDiagnostics(diagnostics, newProgram) {
+ if (!diagnostics.length)
+ return ts.emptyArray;
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToDiagnosticRelatedInformation(diagnostic, newProgram) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && newProgram.getSourceFileByPath(file), messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToDiagnosticMessageChain(messageText, newProgram) });
+ }
+ function convertToDiagnosticMessageChain(diagnostic, newProgram) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram) });
+ }
/**
* Releases program and other related not needed properties
*/
@@ -89659,8 +91287,11 @@
* 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
*/
- function doneWithAffectedFile(state, affected, isPendingEmit) {
- if (affected === state.program) {
+ function doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit) {
+ if (isBuildInfoEmit) {
+ state.emittedBuildInfo = true;
+ }
+ else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
@@ -89677,8 +91308,8 @@
/**
* Returns the result with affected file
*/
- function toAffectedFileResult(state, result, affected, isPendingEmit) {
- doneWithAffectedFile(state, affected, isPendingEmit);
+ function toAffectedFileResult(state, result, affected, isPendingEmit, isBuildInfoEmit) {
+ doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
return { result: result, affected: affected };
}
/**
@@ -89701,6 +91332,77 @@
}
return diagnostics;
}
+ /**
+ * Gets the program information to be emitted in buildInfo so that we can use it to create new program
+ */
+ function getProgramBuildInfo(state) {
+ if (state.compilerOptions.outFile || state.compilerOptions.out)
+ return undefined;
+ var fileInfos = {};
+ state.fileInfos.forEach(function (value, key) {
+ var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
+ fileInfos[key] = signature === undefined ? value : { version: value.version, signature: signature };
+ });
+ var result = { fileInfos: fileInfos, options: state.compilerOptions };
+ if (state.referencedMap) {
+ var referencedMap_1 = {};
+ state.referencedMap.forEach(function (value, key) {
+ referencedMap_1[key] = ts.arrayFrom(value.keys());
+ });
+ result.referencedMap = referencedMap_1;
+ }
+ if (state.exportedModulesMap) {
+ var exportedModulesMap_1 = {};
+ state.exportedModulesMap.forEach(function (value, key) {
+ var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
+ // Not in temporary cache, use existing value
+ if (newValue === undefined)
+ exportedModulesMap_1[key] = ts.arrayFrom(value.keys());
+ // Value in cache and has updated value map, use that
+ else if (newValue)
+ exportedModulesMap_1[key] = ts.arrayFrom(newValue.keys());
+ });
+ result.exportedModulesMap = exportedModulesMap_1;
+ }
+ if (state.semanticDiagnosticsPerFile) {
+ var semanticDiagnosticsPerFile_1 = [];
+ // Currently not recording actual errors since those mean no emit for tsc --build
+ state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ?
+ [
+ key,
+ state.hasReusableDiagnostic ?
+ value :
+ convertToReusableDiagnostics(value)
+ ] :
+ key); });
+ result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1;
+ }
+ return result;
+ }
+ function convertToReusableDiagnostics(diagnostics) {
+ ts.Debug.assert(!!diagnostics.length);
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToReusableDiagnosticRelatedInformation(diagnostic);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToReusableDiagnosticRelatedInformation(diagnostic) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && file.path, messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToReusableDiagnosticMessageChain(messageText) });
+ }
+ function convertToReusableDiagnosticMessageChain(diagnostic) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next) });
+ }
var BuilderProgramKind;
(function (BuilderProgramKind) {
BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
@@ -89757,6 +91459,7 @@
var computeHash = host.createHash || ts.generateDjb2Hash;
var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
var backupState;
+ newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state); };
// To ensure that we arent storing any references to old program or new program without state
newProgram = undefined; // TODO: GH#18217
oldProgram = undefined;
@@ -89800,8 +91503,17 @@
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
affected = getNextAffectedFilePendingEmit(state);
if (!affected) {
+ if (state.emittedBuildInfo) {
return undefined;
}
+ var affected_1 = ts.Debug.assertDefined(state.program);
+ return toAffectedFileResult(state,
+ // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
+ // Otherwise just affected file
+ affected_1.emitBuildInfo(writeFile || host.writeFile, cancellationToken), affected_1,
+ /*isPendingEmitFile*/ false,
+ /*isBuildInfoEmit*/ true);
+ }
isPendingEmitFile = true;
}
else {
@@ -89926,13 +91638,60 @@
}
var diagnostics;
for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
- var sourceFile_2 = _a[_i];
- diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken));
+ var sourceFile_1 = _a[_i];
+ diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
}
return diagnostics || ts.emptyArray;
}
}
ts.createBuilderProgram = createBuilderProgram;
+ function getMapOfReferencedSet(mapLike) {
+ if (!mapLike)
+ return undefined;
+ var map = ts.createMap();
+ // Copies keys/values from template. Note that for..in will not throw if
+ // template is undefined, and instead will just exit the loop.
+ for (var key in mapLike) {
+ if (ts.hasProperty(mapLike, key)) {
+ map.set(key, ts.arrayToSet(mapLike[key]));
+ }
+ }
+ return map;
+ }
+ function createBuildProgramUsingProgramBuildInfo(program) {
+ var fileInfos = ts.createMapFromTemplate(program.fileInfos);
+ var state = {
+ fileInfos: fileInfos,
+ compilerOptions: program.options,
+ referencedMap: getMapOfReferencedSet(program.referencedMap),
+ exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
+ semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return ts.isString(value) ? value : value[0]; }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
+ hasReusableDiagnostic: true
+ };
+ return {
+ getState: function () { return state; },
+ backupState: ts.noop,
+ restoreState: ts.noop,
+ getProgram: ts.notImplemented,
+ getProgramOrUndefined: ts.returnUndefined,
+ releaseProgram: ts.noop,
+ getCompilerOptions: function () { return state.compilerOptions; },
+ getSourceFile: ts.notImplemented,
+ getSourceFiles: ts.notImplemented,
+ getOptionsDiagnostics: ts.notImplemented,
+ getGlobalDiagnostics: ts.notImplemented,
+ getConfigFileParsingDiagnostics: ts.notImplemented,
+ getSyntacticDiagnostics: ts.notImplemented,
+ getDeclarationDiagnostics: ts.notImplemented,
+ getSemanticDiagnostics: ts.notImplemented,
+ emit: ts.notImplemented,
+ getAllDependencies: ts.notImplemented,
+ getCurrentDirectory: ts.notImplemented,
+ emitNextAffectedFile: ts.notImplemented,
+ getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
+ };
+ }
+ ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
return {
getState: ts.notImplemented,
@@ -89952,7 +91711,7 @@
getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
getAllDependencies: ts.notImplemented,
- getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); }
+ getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
};
function getProgram() {
return ts.Debug.assertDefined(state.program);
@@ -89978,10 +91737,10 @@
/*@internal*/
var ts;
(function (ts) {
- function isPathInNodeModulesStartingWithDot(path) {
- return ts.stringContains(path, "/node_modules/.");
+ function isPathIgnored(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); });
}
- ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot;
+ ts.isPathIgnored = isPathIgnored;
ts.maxNumberOfFilesToIterateForInvalidation = 256;
function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
var filesWithChangedSetOfUnresolvedImports;
@@ -90503,7 +92262,7 @@
}
else {
// If something to do with folder/file starting with "." in node_modules folder, skip it
- if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (isPathIgnored(fileOrDirectoryPath))
return false;
// Some file or directory in the watching directory is created
// Return early if it does not have any of the watching extension or not the custom failed lookup path
@@ -90980,6 +92739,8 @@
case ".jsx" /* Jsx */:
case ".json" /* Json */:
return ext;
+ case ".tsbuildinfo" /* TsBuildInfo */:
+ return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
default:
return ts.Debug.assertNever(ext);
}
@@ -91100,22 +92861,18 @@
var diagnostics = program.getConfigFileParsingDiagnostics().slice();
var configFileParsingDiagnosticsLength = diagnostics.length;
ts.addRange(diagnostics, program.getSyntacticDiagnostics());
- var reportSemanticDiagnostics = false;
// If we didn't have any syntactic errors, then also try getting the global and
// semantic errors.
if (diagnostics.length === configFileParsingDiagnosticsLength) {
ts.addRange(diagnostics, program.getOptionsDiagnostics());
ts.addRange(diagnostics, program.getGlobalDiagnostics());
if (diagnostics.length === configFileParsingDiagnosticsLength) {
- reportSemanticDiagnostics = true;
+ ts.addRange(diagnostics, program.getSemanticDiagnostics());
}
}
// Emit and report any errors we ran into.
var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics;
ts.addRange(diagnostics, emitDiagnostics);
- if (reportSemanticDiagnostics) {
- ts.addRange(diagnostics, program.getSemanticDiagnostics());
- }
ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic);
if (writeFileName) {
var currentDir_1 = program.getCurrentDirectory();
@@ -91236,6 +92993,22 @@
}
}
ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
+ function setGetSourceFileAsHashVersioned(compilerHost, host) {
+ var originalGetSourceFile = compilerHost.getSourceFile;
+ var computeHash = host.createHash || ts.generateDjb2Hash;
+ compilerHost.getSourceFile = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
+ if (result) {
+ result.version = computeHash.call(host, result.text);
+ }
+ return result;
+ };
+ }
+ ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
/**
* Creates the watch compiler host that can be extended with config file or root file names and options host
*/
@@ -91261,7 +93034,7 @@
writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
createHash: ts.maybeBind(system, system.createHash),
- createProgram: createProgram
+ createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
};
}
ts.createProgramHost = createProgramHost;
@@ -91271,7 +93044,7 @@
function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
var writeFileName = function (s) { return system.write(s + system.newLine); };
- var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram);
+ var result = createProgramHost(system, createProgram);
ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = function (builderProgram) {
var compilerOptions = builderProgram.getCompilerOptions();
@@ -91310,6 +93083,49 @@
return host;
}
ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
+ function readBuilderProgram(compilerOptions, readFile) {
+ if (compilerOptions.out || compilerOptions.outFile)
+ return undefined;
+ var buildInfoPath = ts.getOutputPathForBuildInfo(compilerOptions);
+ if (!buildInfoPath)
+ return undefined;
+ var content = readFile(buildInfoPath);
+ if (!content)
+ return undefined;
+ var buildInfo = ts.getBuildInfo(content);
+ if (buildInfo.version !== ts.version)
+ return undefined;
+ if (!buildInfo.program)
+ return undefined;
+ return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program);
+ }
+ ts.readBuilderProgram = readBuilderProgram;
+ function createIncrementalCompilerHost(options, system) {
+ if (system === void 0) { system = ts.sys; }
+ var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
+ host.createHash = ts.maybeBind(system, system.createHash);
+ setGetSourceFileAsHashVersioned(host, system);
+ ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
+ return host;
+ }
+ ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
+ function createIncrementalProgram(_a) {
+ var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
+ host = host || createIncrementalCompilerHost(options);
+ createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
+ var oldProgram = readBuilderProgram(options, function (path) { return host.readFile(path); });
+ return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
+ }
+ function performIncrementalCompilation(input) {
+ var system = input.system || ts.sys;
+ var host = input.host || (input.host = createIncrementalCompilerHost(input.options, system));
+ var builderProgram = createIncrementalProgram(input);
+ var exitStatus = emitFilesAndReportErrors(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined);
+ if (input.afterProgramEmitAndDiagnostics)
+ input.afterProgramEmitAndDiagnostics(builderProgram);
+ return exitStatus;
+ }
+ ts.performIncrementalCompilation = performIncrementalCompilation;
})(ts || (ts = {}));
(function (ts) {
function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) {
@@ -91321,7 +93137,6 @@
}
}
ts.createWatchCompilerHost = createWatchCompilerHost;
- var initialVersion = 1;
function createWatchProgram(host) {
var builderProgram;
var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
@@ -91362,10 +93177,12 @@
var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
+ var configFileWatcher;
if (configFileName) {
- watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */);
+ configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */);
}
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
+ ts.setGetSourceFileAsHashVersioned(compilerHost, host);
// Members for CompilerHost
var getNewSourceFile = compilerHost.getSourceFile;
compilerHost.getSourceFile = function (fileName) {
@@ -91406,21 +93223,43 @@
(function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) :
(function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
+ builderProgram = ts.readBuilderProgram(compilerOptions, function (path) { return compilerHost.readFile(path); });
synchronizeProgram();
// Update the wild card directory watch
watchConfigFileWildCardDirectories();
return configFileName ?
- { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } :
- { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames };
+ { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } :
+ { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close };
+ function close() {
+ resolutionCache.clear();
+ ts.clearMap(sourceFilesCache, function (value) {
+ if (value && value.fileWatcher) {
+ value.fileWatcher.close();
+ value.fileWatcher = undefined;
+ }
+ });
+ if (configFileWatcher) {
+ configFileWatcher.close();
+ configFileWatcher = undefined;
+ }
+ if (watchedWildcardDirectories) {
+ ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
+ watchedWildcardDirectories = undefined;
+ }
+ if (missingFilesMap) {
+ ts.clearMap(missingFilesMap, ts.closeFileWatcher);
+ missingFilesMap = undefined;
+ }
+ }
function getCurrentBuilderProgram() {
return builderProgram;
}
function getCurrentProgram() {
- return builderProgram && builderProgram.getProgram();
+ return builderProgram && builderProgram.getProgramOrUndefined();
}
function synchronizeProgram() {
writeLog("Synchronizing program");
- var program = getCurrentProgram();
+ var program = getCurrentBuilderProgram();
if (hasChangedCompilerOptions) {
newLine = updateNewLine();
if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
@@ -91436,19 +93275,19 @@
}
}
else {
- createNewProgram(program, hasInvalidatedResolution);
+ createNewProgram(hasInvalidatedResolution);
}
if (host.afterProgramCreate) {
host.afterProgramCreate(builderProgram);
}
return builderProgram;
}
- function createNewProgram(program, hasInvalidatedResolution) {
+ function createNewProgram(hasInvalidatedResolution) {
// Compile the program
writeLog("CreatingProgramWith::");
writeLog(" roots: " + JSON.stringify(rootFileNames));
writeLog(" options: " + JSON.stringify(compilerOptions));
- var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program;
+ var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
hasChangedCompilerOptions = false;
hasChangedConfigFileParsingErrors = false;
resolutionCache.startCachingPerDirectoryResolution();
@@ -91488,10 +93327,10 @@
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
}
function isFileMissingOnHost(hostSourceFile) {
- return typeof hostSourceFile === "number";
+ return typeof hostSourceFile === "boolean";
}
- function isFilePresentOnHost(hostSourceFile) {
- return !!hostSourceFile.sourceFile;
+ function isFilePresenceUnknownOnHost(hostSourceFile) {
+ return typeof hostSourceFile.version === "boolean";
}
function fileExists(fileName) {
var path = toPath(fileName);
@@ -91509,36 +93348,32 @@
return undefined;
}
// Create new source file if requested or the versions dont match
- if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) {
+ if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
if (hostSourceFile) {
- if (shouldCreateNewSourceFile) {
- hostSourceFile.version++;
- }
if (sourceFile) {
// Set the source file and create file watcher now that file was present on the disk
hostSourceFile.sourceFile = sourceFile;
- sourceFile.version = hostSourceFile.version.toString();
+ hostSourceFile.version = sourceFile.version;
if (!hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */);
}
}
else {
// There is no source file on host any more, close the watch, missing file paths will track it
- if (isFilePresentOnHost(hostSourceFile)) {
+ if (hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher.close();
}
- sourceFilesCache.set(path, hostSourceFile.version);
+ sourceFilesCache.set(path, false);
}
}
else {
if (sourceFile) {
- sourceFile.version = initialVersion.toString();
var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */);
- sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher });
+ sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
}
else {
- sourceFilesCache.set(path, initialVersion);
+ sourceFilesCache.set(path, false);
}
}
return sourceFile;
@@ -91550,16 +93385,16 @@
if (hostSourceFile !== undefined) {
if (isFileMissingOnHost(hostSourceFile)) {
// The next version, lets set it as presence unknown file
- sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 });
+ sourceFilesCache.set(path, { version: false });
}
else {
- hostSourceFile.version++;
+ hostSourceFile.version = false;
}
}
}
function getSourceVersion(path) {
var hostSourceFile = sourceFilesCache.get(path);
- return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString();
+ return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
}
function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
@@ -91567,7 +93402,7 @@
// remove the cached entry.
// Note we arent deleting entry if file became missing in new program or
// there was version update and new source file was created.
- if (hostSourceFileInfo) {
+ if (hostSourceFileInfo !== undefined) {
// record the missing file paths so they can be removed later if watchers arent tracking them
if (isFileMissingOnHost(hostSourceFileInfo)) {
(missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
@@ -91656,7 +93491,7 @@
function onSourceFileChange(fileName, eventKind, path) {
updateCachedSystemWithFile(fileName, path, eventKind);
// Update the source file cache
- if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) {
+ if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
resolutionCache.invalidateResolutionOfFile(path);
}
resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
@@ -91700,7 +93535,7 @@
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
nextSourceFileVersion(fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
// 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
@@ -91754,16 +93589,23 @@
* This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
*/
UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
- UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream";
- UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate";
- UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked";
- UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream";
+ /**
+ * The project appears out of date because its upstream inputs are newer than its outputs,
+ * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
+ * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
+ */
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
+ UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
+ UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
+ UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
+ UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
+ UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
/**
* Projects with no outputs (i.e. "solution" files)
*/
- UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly";
+ UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
})(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
function createFileMap(toPath) {
// tslint:disable-next-line:no-null-keyword
@@ -91811,61 +93653,6 @@
function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
}
- 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);
- return ts.changeExtension(outputPath, ".d.ts" /* Dts */);
- }
- ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
- function getOutputJSFileName(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);
- 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) {
- // 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 = [];
- var js = getOutputJSFileName(inputFileName, configFile);
- outputs.push(js);
- if (configFile.options.sourceMap) {
- outputs.push(js + ".map");
- }
- 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");
- }
- }
- return outputs;
- }
- function getOutFileOutputs(project) {
- var out = project.options.outFile || project.options.out;
- if (!out) {
- return ts.Debug.fail("outFile must be set");
- }
- var outputs = [];
- outputs.push(out);
- if (project.options.sourceMap) {
- outputs.push(out + ".map");
- }
- if (ts.getEmitDeclarations(project.options)) {
- var dts = ts.changeExtension(out, ".d.ts" /* Dts */);
- outputs.push(dts);
- if (project.options.declarationMap) {
- outputs.push(dts + ".map");
- }
- }
- return outputs;
- }
- function rootDirOfOptions(opts, configFileName) {
- return opts.rootDir || ts.getDirectoryPath(configFileName);
- }
function newer(date1, date2) {
return date2 > date1 ? date2 : date1;
}
@@ -91885,7 +93672,7 @@
ts.createBuilderStatusReporter = createBuilderStatusReporter;
function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
var host = ts.createProgramHost(system, createProgram);
- host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; };
+ host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
@@ -91894,14 +93681,14 @@
}
function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
host.reportErrorSummary = reportErrorSummary;
return host;
}
ts.createSolutionBuilderHost = createSolutionBuilderHost;
function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
var watchHost = ts.createWatchHost(system, reportWatchStatus);
ts.copyProperties(host, watchHost);
return host;
@@ -91933,9 +93720,8 @@
var readFileWithCache = function (f) { return host.readFile(f); };
var projectCompilerOptions = baseCompilerOptions;
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; });
- var originalGetSourceFile = compilerHost.getSourceFile;
- var computeHash = host.createHash || ts.generateDjb2Hash;
- updateGetSourceFile();
+ ts.setGetSourceFileAsHashVersioned(compilerHost, host);
+ var buildInfoChecked = createFileMap(toPath);
// Watch state
var builderPrograms = createFileMap(toPath);
var diagnostics = createFileMap(toPath);
@@ -91973,6 +93759,7 @@
projectStatus.clear();
missingRoots.clear();
globalDependencyGraph = undefined;
+ buildInfoChecked.clear();
diagnostics.clear();
projectPendingBuild.clear();
projectErrorsReported.clear();
@@ -91987,29 +93774,6 @@
ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); });
ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher);
builderPrograms.clear();
- updateGetSourceFile();
- }
- function updateGetSourceFile() {
- if (options.watch) {
- if (compilerHost.getSourceFile === originalGetSourceFile) {
- compilerHost.getSourceFile = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
- if (result && options.watch) {
- result.version = computeHash.call(host, result.text);
- }
- return result;
- };
- }
- }
- else {
- if (compilerHost.getSourceFile !== originalGetSourceFile) {
- compilerHost.getSourceFile = originalGetSourceFile;
- }
- }
}
function isParsedCommandLine(entry) {
return !!entry.options;
@@ -92160,13 +93924,14 @@
newestInputFileTime = inputTime;
}
}
- // Collect the expected outputs of this project
- var outputs = getAllProjectOutputs(project);
- if (outputs.length === 0) {
+ // Container if no files are specified in the project
+ if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) {
return {
type: UpToDateStatusType.ContainerOnly
};
}
+ // Collect the expected outputs of this project
+ var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
// Now see if all outputs are newer than the newest input
var oldestOutputFileName = "(none)";
var oldestOutputFileTime = maximumDate;
@@ -92241,6 +94006,8 @@
upstreamProjectName: ref.path
};
}
+ // Check oldest output file name only if there is no missing output file name
+ if (!missingOutputFileName) {
// 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) {
@@ -92262,6 +94029,7 @@
};
}
}
+ }
if (missingOutputFileName !== undefined) {
return {
type: UpToDateStatusType.OutputMissing,
@@ -92275,9 +94043,33 @@
newerInputFileName: newestInputFileName
};
}
+ else {
+ // Check tsconfig time
+ var configStatus = checkConfigFileUpToDateStatus(project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
+ if (configStatus)
+ return configStatus;
+ // Check extended config time
+ var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName); });
+ if (extendedConfigStatus)
+ return extendedConfigStatus;
+ }
+ if (!buildInfoChecked.hasKey(project.options.configFilePath)) {
+ buildInfoChecked.setValue(project.options.configFilePath, true);
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath) {
+ var value = readFileWithCache(buildInfoPath);
+ var buildInfo = value && ts.getBuildInfo(value);
+ if (buildInfo && buildInfo.version !== ts.version) {
+ return {
+ type: UpToDateStatusType.TsVersionOutputOfDate,
+ version: buildInfo.version
+ };
+ }
+ }
+ }
if (usesPrepend && pseudoUpToDate) {
return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
+ type: UpToDateStatusType.OutOfDateWithPrepend,
outOfDateOutputFileName: oldestOutputFileName,
newerProjectName: upstreamChangedProject
};
@@ -92293,6 +94085,17 @@
oldestOutputFileName: oldestOutputFileName
};
}
+ function checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName) {
+ // Check tsconfig time
+ var tsconfigTime = host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
+ if (oldestOutputFileTime < tsconfigTime) {
+ return {
+ type: UpToDateStatusType.OutOfDateWithSelf,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerInputFileName: configFile
+ };
+ }
+ }
function invalidateProject(configFileName, reloadLevel) {
invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel);
}
@@ -92411,7 +94214,9 @@
updateOutputTimestamps(proj);
return;
}
- var buildResult = buildSingleProject(resolved);
+ var buildResult = needsBuild(status, resolved) ?
+ buildSingleProject(resolved) : // Actual build
+ updateBundle(resolved); // Fake that files have been built by manipulating prepend and existing output
if (buildResult & BuildResultFlags.AnyErrors)
return;
var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue;
@@ -92427,18 +94232,27 @@
// If declaration output is changed, build the project
// otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
var status_1 = projectStatus.getValue(project);
- if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
- if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) {
+ if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
+ if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status_1.type === UpToDateStatusType.OutOfDateWithPrepend)) {
projectStatus.setValue(project, {
type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: status_1.oldestOutputFileName,
+ outOfDateOutputFileName: status_1.type === UpToDateStatusType.OutOfDateWithPrepend ? status_1.outOfDateOutputFileName : status_1.oldestOutputFileName,
newerProjectName: resolved
});
}
}
else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) {
+ if (prepend) {
+ projectStatus.setValue(project, {
+ type: UpToDateStatusType.OutOfDateWithPrepend,
+ outOfDateOutputFileName: status_1.oldestOutputFileName,
+ newerProjectName: resolved
+ });
+ }
+ else {
status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
}
+ }
addProjToQueue(project);
}
}
@@ -92494,8 +94308,7 @@
}
if (options.verbose)
reportStatus(ts.Diagnostics.Building_project_0, proj);
- var resultFlags = BuildResultFlags.None;
- resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
+ var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
var configFile = parseConfigFile(proj);
if (!configFile) {
// Failed to read the config file
@@ -92511,8 +94324,7 @@
}
// TODO: handle resolve module name to cache result in project reference redirect
projectCompilerOptions = configFile.options;
- var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences);
- projectCompilerOptions = baseCompilerOptions;
+ var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, getOldProgram(proj, configFile), configFile.errors, configFile.projectReferences);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
@@ -92568,17 +94380,19 @@
var status = {
type: UpToDateStatusType.UpToDate,
newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime,
- oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile)
+ oldestOutputFileName: outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(configFile, !host.useCaseSensitiveFileNames())
};
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
}
}
@@ -92591,15 +94405,71 @@
builderPrograms.setValue(proj, program);
}
}
+ function getOldProgram(proj, parsed) {
+ if (options.force)
+ return undefined;
+ var value = builderPrograms.getValue(proj);
+ if (value)
+ return value;
+ return ts.readBuilderProgram(parsed.options, readFileWithCache);
+ }
+ function updateBundle(proj) {
+ if (options.dry) {
+ reportStatus(ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
+ return BuildResultFlags.Success;
+ }
+ if (options.verbose)
+ reportStatus(ts.Diagnostics.Updating_output_of_project_0, proj);
+ // Update js, and source map
+ var config = ts.Debug.assertDefined(parseConfigFile(proj));
+ projectCompilerOptions = config.options;
+ var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) { return parseConfigFile(resolveProjectName(ref.path)); });
+ if (ts.isString(outputFiles)) {
+ reportStatus(ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
+ return buildSingleProject(proj);
+ }
+ // Actual Emit
+ ts.Debug.assert(!!outputFiles.length);
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ var emittedOutputs = createFileMap(toPath);
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
+ emittedOutputs.setValue(name, true);
+ ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
+ });
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
+ reportAndStoreErrors(proj, emitDiagnostics);
+ projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
+ }
+ // Update timestamps for dts
+ var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
+ oldestOutputFileName: outputFiles[0].name
+ };
+ diagnostics.removeKey(proj);
+ projectStatus.setValue(proj, status);
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged;
+ }
function updateOutputTimestamps(proj) {
if (options.dry) {
- return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
+ return reportStatus(ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
}
var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
- projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
+ oldestOutputFileName: ts.getFirstProjectOutput(proj, !host.useCaseSensitiveFileNames())
+ };
+ projectStatus.setValue(proj.options.configFilePath, status);
}
function updateOutputTimestampsWorker(proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
- var outputs = getAllProjectOutputs(proj);
+ var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
if (!skipOutputs || outputs.length !== skipOutputs.getSize()) {
if (options.verbose) {
reportStatus(verboseMessage, proj.options.configFilePath);
@@ -92633,7 +94503,7 @@
reportParseConfigFileDiagnostic(proj);
continue;
}
- var outputs = getAllProjectOutputs(parsed);
+ var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) {
var output = outputs_3[_b];
if (host.fileExists(output)) {
@@ -92720,7 +94590,9 @@
// Do nothing
continue;
}
- var buildResult = buildSingleProject(next);
+ var buildResult = needsBuild(status, next) ?
+ buildSingleProject(next) : // Actual build
+ updateBundle(next); // Fake that files have been built by manipulating prepend and existing output
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
@@ -92733,6 +94605,15 @@
readFileWithCache = savedReadFileWithCache;
return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
}
+ function needsBuild(status, configFile) {
+ if (status.type !== UpToDateStatusType.OutOfDateWithPrepend || options.force)
+ return true;
+ var config = parseConfigFile(configFile);
+ return !config ||
+ config.fileNames.length === 0 ||
+ !!config.errors.length ||
+ !ts.isIncrementalCompilation(config.options);
+ }
function reportParseConfigFileDiagnostic(proj) {
reportAndStoreErrors(proj, [configFileCache.getValue(proj)]);
}
@@ -92772,33 +94653,6 @@
return ts.combinePaths(project, "tsconfig.json");
}
ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
- function getAllProjectOutputs(project) {
- if (project.options.outFile || project.options.out) {
- 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 getFirstProjectOutput(project) {
- if (project.options.outFile || project.options.out) {
- return ts.first(getOutFileOutputs(project));
- }
- for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
- var inputFile = _a[_i];
- var outputs = getOutputFileNames(inputFile, project);
- if (outputs.length) {
- return ts.first(outputs);
- }
- }
- return ts.Debug.fail("project " + project.options.configFilePath + " expected to have at least one output");
- }
function formatUpToDateStatus(configFileName, status, relName, formatMessage) {
switch (status.type) {
case UpToDateStatusType.OutOfDateWithSelf:
@@ -92813,6 +94667,8 @@
}
// Don't report anything for "up to date because it was already built" -- too verbose
break;
+ case UpToDateStatusType.OutOfDateWithPrepend:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(configFileName), relName(status.newerProjectName));
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:
@@ -92821,6 +94677,8 @@
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.TsVersionOutputOfDate:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(configFileName), status.version, ts.version);
case UpToDateStatusType.ContainerOnly:
// Don't report status on "solution" projects
case UpToDateStatusType.ComputingUpstream:
@@ -92970,32 +94828,6 @@
}
}
})(ts || (ts = {}));
-//# sourceMappingURL=compiler.js.map
-"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];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-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) {
var ScriptSnapshot;
@@ -93278,7 +95110,7 @@
/* @internal */
var ts;
(function (ts) {
- ts.scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true);
+ ts.scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ true);
var SemanticMeaning;
(function (SemanticMeaning) {
SemanticMeaning[SemanticMeaning["None"] = 0] = "None";
@@ -93313,7 +95145,7 @@
case 242 /* TypeAliasDeclaration */:
case 168 /* TypeLiteral */:
return 2 /* Type */;
- case 304 /* JSDocTypedefTag */:
+ case 309 /* 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 278 /* EnumMember */:
@@ -93338,14 +95170,14 @@
case 255 /* ExportDeclaration */:
return 7 /* All */;
// An external module can be a Value
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 4 /* Namespace */ | 1 /* Value */;
}
return 7 /* All */;
}
ts.getMeaningFromDeclaration = getMeaningFromDeclaration;
function getMeaningFromLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return 1 /* Value */;
}
else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) {
@@ -93551,7 +95383,7 @@
return undefined;
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
case 239 /* FunctionDeclaration */:
@@ -93569,7 +95401,7 @@
ts.getContainerNode = getContainerNode;
function getNodeKind(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */;
case 244 /* ModuleDeclaration */:
return "module" /* moduleElement */;
@@ -93578,8 +95410,8 @@
return "class" /* classElement */;
case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */;
case 242 /* TypeAliasDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return "type" /* typeElement */;
case 243 /* EnumDeclaration */: return "enum" /* enumElement */;
case 237 /* VariableDeclaration */:
@@ -94005,7 +95837,7 @@
}
}
}
- ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
+ ts.Debug.assert(startNode !== undefined || n.kind === 284 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || 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.
@@ -94092,7 +95924,7 @@
}
ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute;
function isWhiteSpaceOnlyJsxText(node) {
- return ts.isJsxText(node) && node.containsOnlyWhiteSpaces;
+ return ts.isJsxText(node) && node.containsOnlyTriviaWhiteSpaces;
}
function isInTemplateString(sourceFile, position) {
var token = getTokenAtPosition(sourceFile, position);
@@ -94852,6 +96684,17 @@
return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName));
}
ts.getScriptKind = getScriptKind;
+ function getSymbolTarget(symbol) {
+ var next = symbol;
+ while (isTransientSymbol(next) && next.target) {
+ next = next.target;
+ }
+ return next;
+ }
+ ts.getSymbolTarget = getSymbolTarget;
+ function isTransientSymbol(symbol) {
+ return (symbol.flags & 33554432 /* Transient */) !== 0;
+ }
function getUniqueSymbolId(symbol, checker) {
return ts.getSymbolId(ts.skipAlias(symbol, checker));
}
@@ -95003,8 +96846,27 @@
return lastPos;
}
ts.getRenameLocation = getRenameLocation;
- function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
- ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
+ function copyLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyLeadingComments = copyLeadingComments;
+ function copyTrailingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticTrailingComment));
+ }
+ ts.copyTrailingComments = copyTrailingComments;
+ /**
+ * This function copies the trailing comments for the token that comes before `sourceNode`, as leading comments of `targetNode`.
+ * This is useful because sometimes a comment that refers to `sourceNode` will be a leading comment for `sourceNode`, according to the
+ * notion of trivia ownership, and instead will be a trailing comment for the token before `sourceNode`, e.g.:
+ * `function foo(\* not leading comment for a *\ a: string) {}`
+ * The comment refers to `a` but belongs to the `(` token, but we might want to copy it.
+ */
+ function copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyTrailingAsLeadingComments = copyTrailingAsLeadingComments;
+ function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, cb) {
+ return function (pos, end, kind, htnl) {
if (kind === 3 /* MultiLineCommentTrivia */) {
// Remove leading /*
pos += 2;
@@ -95015,10 +96877,9 @@
// Remove leading //
pos += 2;
}
- ts.addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
- });
+ cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
+ };
}
- ts.copyComments = copyComments;
function indexInTextChange(change, name) {
if (ts.startsWith(change, name))
return 0;
@@ -95099,11 +96960,35 @@
return checker.getTypeAtLocation(caseClause.parent.parent.expression);
}
ts.getSwitchedType = getSwitchedType;
+ function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
+ var checker = program.getTypeChecker();
+ var typeIsAccessible = true;
+ var notAccessible = function () { typeIsAccessible = false; };
+ var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
+ trackSymbol: function (symbol, declaration, meaning) {
+ // TODO: GH#18217
+ typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
+ },
+ reportInaccessibleThisError: notAccessible,
+ reportPrivateInBaseOfClassExpression: notAccessible,
+ reportInaccessibleUniqueSymbolError: notAccessible,
+ moduleResolverHost: {
+ readFile: host.readFile,
+ fileExists: host.fileExists,
+ directoryExists: host.directoryExists,
+ getSourceFiles: program.getSourceFiles,
+ getCurrentDirectory: program.getCurrentDirectory,
+ getCommonSourceDirectory: program.getCommonSourceDirectory,
+ }
+ });
+ return typeIsAccessible ? res : undefined;
+ }
+ ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible;
})(ts || (ts = {}));
var ts;
(function (ts) {
function createClassifier() {
- var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false);
+ var scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false);
function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) {
return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text);
}
@@ -95657,8 +97542,8 @@
var spanStart = span.start;
var spanLength = span.length;
// Make a scanner we can get trivia from.
- var triviaScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
- var mergeConflictScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
+ var triviaScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
+ var mergeConflictScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
var result = [];
processElement(sourceFile);
return { spans: result, endOfLineState: 0 /* None */ };
@@ -95750,18 +97635,18 @@
pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param"
pos = tag.tagName.end;
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
processJSDocParameterTag(tag);
break;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
processJSDocTemplateTag(tag);
pos = tag.end;
break;
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
@@ -96014,7 +97899,7 @@
return convertPathCompletions(completion.paths);
case 1 /* Properties */: {
var entries = [];
- Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary
+ Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 7 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries };
}
case 2 /* Types */: {
@@ -96065,6 +97950,7 @@
case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */;
case ".ts" /* Ts */: return ".ts" /* tsModifier */;
case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */;
+ case ".tsbuildinfo" /* TsBuildInfo */: return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported.");
case undefined: return "" /* none */;
default:
return ts.Debug.assertNever(extension);
@@ -96592,7 +98478,7 @@
var offset = index !== -1 ? index + 1 : 0;
// If the range is an identifier, span is unnecessary.
var length = text.length - offset;
- return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length);
+ return length === 0 || ts.isIdentifierText(text.substr(offset, length), 7 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length);
}
// Returns true if the path is explicitly relative to the script (i.e. relative to . or ..)
function isPathRelativeToScript(path) {
@@ -96677,6 +98563,7 @@
KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords";
KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords";
KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords";
+ KeywordCompletionFilters[KeywordCompletionFilters["Last"] = 6] = "Last";
})(KeywordCompletionFilters || (KeywordCompletionFilters = {}));
var GlobalsSearch;
(function (GlobalsSearch) {
@@ -96722,7 +98609,7 @@
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
}
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;
+ 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, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression;
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.
@@ -96753,7 +98640,7 @@
}
if (keywordFilters !== 0 /* None */) {
var entryNames = ts.arrayToSet(entries, function (e) { return e.name; });
- for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) {
var keywordEntry = _a[_i];
if (!entryNames.has(keywordEntry.name)) {
entries.push(keywordEntry);
@@ -97089,7 +98976,7 @@
return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
}
function isModuleSymbol(symbol) {
- return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; });
+ return symbol.declarations.some(function (d) { return d.kind === 284 /* SourceFile */; });
}
function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) {
var typeChecker = program.getTypeChecker();
@@ -97140,11 +99027,11 @@
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
return { kind: 1 /* JsDocTagName */ };
}
- if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
currentToken = ts.getTokenAtPosition(sourceFile, position);
if (!currentToken ||
(!ts.isDeclarationName(currentToken) &&
- (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ ||
+ (currentToken.parent.kind !== 310 /* JSDocPropertyTag */ ||
currentToken.parent.name !== currentToken))) {
// Use as type location if inside tag's type expression
insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
@@ -97197,6 +99084,14 @@
case 189 /* PropertyAccessExpression */:
propertyAccessToConvert = parent;
node = propertyAccessToConvert.expression;
+ if (node.end === contextToken.pos &&
+ ts.isCallExpression(node) &&
+ node.getChildCount(sourceFile) &&
+ ts.last(node.getChildren(sourceFile)).kind !== 21 /* CloseParenToken */) {
+ // This is likely dot from incorrectly parsed call expression and user is starting to write spread
+ // eg: Math.min(./**/)
+ return undefined;
+ }
break;
case 148 /* QualifiedName */:
node = parent.left;
@@ -97312,14 +99207,29 @@
var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker);
var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; });
var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker);
- 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 };
+ 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,
+ insideJsDocTagTypeExpression: insideJsDocTagTypeExpression
+ };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 304 /* JSDocTypedefTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 309 /* JSDocTypedefTag */:
return true;
default:
return false;
@@ -97359,7 +99269,9 @@
}
}
// 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 !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
+ if (!isTypeLocation &&
+ symbol.declarations &&
+ symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node));
}
return;
@@ -97492,8 +99404,8 @@
var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 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 !== 279 /* SourceFile */) {
- var thisType = typeChecker.tryGetThisTypeAt(scopeNode);
+ if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 284 /* SourceFile */) {
+ var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false);
if (thisType) {
for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) {
var symbol = _a[_i];
@@ -97525,7 +99437,7 @@
}
function isSnippetScope(scopeNode) {
switch (scopeNode.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 206 /* TemplateExpression */:
case 270 /* JsxExpression */:
case 218 /* Block */:
@@ -97584,6 +99496,8 @@
return parentKind === 242 /* TypeAliasDeclaration */;
case 119 /* AsKeyword */:
return parentKind === 212 /* AsExpression */;
+ case 86 /* ExtendsKeyword */:
+ return parentKind === 150 /* TypeParameter */;
}
}
return false;
@@ -98280,7 +100194,15 @@
}
return res;
});
- function getKeywordCompletions(keywordFilter) {
+ function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) {
+ if (!filterOutTsOnlyKeywords)
+ return getTypescriptKeywordCompletions(keywordFilter);
+ var index = keywordFilter + 6 /* Last */ + 1;
+ return _keywordCompletions[index] ||
+ (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter)
+ .filter(function (entry) { return !isTypeScriptOnlyKeyword(ts.stringToToken(entry.name)); }));
+ }
+ function getTypescriptKeywordCompletions(keywordFilter) {
return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) {
var kind = ts.stringToToken(entry.name);
switch (keywordFilter) {
@@ -98304,6 +100226,39 @@
}
}));
}
+ function isTypeScriptOnlyKeyword(kind) {
+ switch (kind) {
+ case 118 /* AbstractKeyword */:
+ case 120 /* AnyKeyword */:
+ case 146 /* BigIntKeyword */:
+ case 123 /* BooleanKeyword */:
+ case 125 /* DeclareKeyword */:
+ case 84 /* EnumKeyword */:
+ case 145 /* GlobalKeyword */:
+ case 109 /* ImplementsKeyword */:
+ case 127 /* InferKeyword */:
+ case 110 /* InterfaceKeyword */:
+ case 128 /* IsKeyword */:
+ case 129 /* KeyOfKeyword */:
+ case 130 /* ModuleKeyword */:
+ case 131 /* NamespaceKeyword */:
+ case 132 /* NeverKeyword */:
+ case 135 /* NumberKeyword */:
+ case 136 /* ObjectKeyword */:
+ case 113 /* PrivateKeyword */:
+ case 114 /* ProtectedKeyword */:
+ case 115 /* PublicKeyword */:
+ case 133 /* ReadonlyKeyword */:
+ case 138 /* StringKeyword */:
+ case 139 /* SymbolKeyword */:
+ case 140 /* TypeKeyword */:
+ case 142 /* UniqueKeyword */:
+ case 143 /* UnknownKeyword */:
+ return true;
+ default:
+ return false;
+ }
+ }
function isInterfaceOrTypeLiteralCompletionKeyword(kind) {
return kind === 133 /* ReadonlyKeyword */;
}
@@ -98357,7 +100312,7 @@
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 306 /* SyntaxList */:
+ case 311 /* 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);
@@ -98542,7 +100497,7 @@
var child = throwStatement;
while (child.parent) {
var parent = child.parent;
- if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) {
+ if (ts.isFunctionBlock(parent) || parent.kind === 284 /* SourceFile */) {
return parent;
}
// A throw-statement is only owned by a try-statement if the try-statement has
@@ -98600,7 +100555,7 @@
var container = declaration.parent;
switch (container.kind) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 271 /* CaseClause */:
case 272 /* DefaultClause */:
@@ -99098,7 +101053,7 @@
}
else if (!isAvailableThroughGlobal) {
var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
- ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
+ ts.Debug.assert(sourceFileLike.kind === 284 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
addIndirectUsers(sourceFileLike);
}
@@ -99207,7 +101162,7 @@
}
}
/**
- * `import x = require("./x") or `import * as x from "./x"`.
+ * `import x = require("./x")` or `import * as x from "./x"`.
* An `export =` may be imported by this syntax, so it may be a direct import.
* If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here.
*/
@@ -99267,7 +101222,7 @@
for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
var referencingFile = sourceFiles_1[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
- if (searchSourceFile.kind === 279 /* SourceFile */) {
+ if (searchSourceFile.kind === 284 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
var ref = _b[_a];
if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
@@ -99315,7 +101270,7 @@
}
/** 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 === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
+ return ts.forEach(sourceFileLike.kind === 284 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action));
});
}
@@ -99539,7 +101494,7 @@
return node.getSourceFile();
}
var parent = node.parent;
- if (parent.kind === 279 /* SourceFile */) {
+ if (parent.kind === 284 /* SourceFile */) {
return parent;
}
ts.Debug.assert(parent.kind === 245 /* ModuleBlock */);
@@ -99601,7 +101556,7 @@
}
FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition;
function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return undefined;
}
var checker = program.getTypeChecker();
@@ -99821,8 +101776,8 @@
case 248 /* ImportEqualsDeclaration */:
case 253 /* ImportSpecifier */:
case 241 /* InterfaceDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
case 267 /* JsxAttribute */:
case 244 /* ModuleDeclaration */:
case 247 /* NamespaceExportDeclaration */:
@@ -99847,8 +101802,8 @@
return !!decl.initializer || ts.isCatchClause(decl.parent);
case 155 /* MethodSignature */:
case 153 /* PropertySignature */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
return false;
default:
return ts.Debug.failBadSyntaxKind(decl);
@@ -100008,7 +101963,7 @@
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
switch (decl.kind) {
- case 279 /* SourceFile */:
+ case 284 /* 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 244 /* ModuleDeclaration */:
@@ -100081,11 +102036,16 @@
}
else {
var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] });
+ getReferencesInContainerOrFiles(symbol, state, search);
+ }
+ return result;
+ }
+ function getReferencesInContainerOrFiles(symbol, state, search) {
// Try to get the smallest valid scope that we can limit our search to;
// otherwise we'll need to search globally (i.e. include each file).
var scope = getSymbolScope(symbol);
if (scope) {
- getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope)));
+ getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(state.sourceFiles, scope)));
}
else {
// Global search
@@ -100096,8 +102056,6 @@
}
}
}
- return result;
- }
function getSpecialSearchKind(node) {
switch (node.kind) {
case 124 /* ConstructorKeyword */:
@@ -100149,9 +102107,7 @@
* Unlike `Search`, there is only one `State`.
*/
var State = /** @class */ (function () {
- function State(sourceFiles, sourceFilesSet,
- /** True if we're searching for constructor references. */
- specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
+ function State(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
this.sourceFiles = sourceFiles;
this.sourceFilesSet = sourceFilesSet;
this.specialSearchKind = specialSearchKind;
@@ -100379,7 +102335,7 @@
// Different declarations have different containers, bail out
return undefined;
}
- if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
+ if (!container || container.kind === 284 /* 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;
@@ -100466,8 +102422,8 @@
// We found a match. Make sure it's not part of a larger word (i.e. the char
// before and after it have to be a non-identifier char).
var endPosition = position + symbolNameLength;
- if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 6 /* Latest */)) &&
- (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 6 /* Latest */))) {
+ if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 7 /* Latest */)) &&
+ (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 7 /* Latest */))) {
// Found a real match. Keep searching.
positions.push(position);
}
@@ -100616,7 +102572,9 @@
}
// For `export { foo as bar }`, rename `foo`, but not `bar`.
if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) {
- var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */;
+ var isDefaultExport = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */
+ || exportSpecifier.name.originalKeywordKind === 80 /* DefaultKeyword */;
+ var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */;
var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol);
var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker));
searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
@@ -100703,6 +102661,7 @@
var classExtending = tryGetClassByExtendingIdentifier(referenceLocation);
if (classExtending) {
findSuperConstructorAccesses(classExtending, pusher());
+ findInheritedConstructorReferences(classExtending, state);
}
}
}
@@ -100735,12 +102694,16 @@
* Reference the constructor and all calls to `new this()`.
*/
function findOwnConstructorReferences(classSymbol, sourceFile, addNode) {
- for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) {
+ var constructorSymbol = getClassConstructorSymbol(classSymbol);
+ if (constructorSymbol) {
+ for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile);
ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword);
addNode(ctrKeyword);
}
+ }
+ if (classSymbol.exports) {
classSymbol.exports.forEach(function (member) {
var decl = member.valueDeclaration;
if (decl && decl.kind === 156 /* MethodDeclaration */) {
@@ -100755,13 +102718,17 @@
}
});
}
+ }
+ function getClassConstructorSymbol(classSymbol) {
+ return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */);
+ }
/** Find references to `super` in the constructor of an extending class. */
- function findSuperConstructorAccesses(cls, addNode) {
- var ctr = cls.symbol.members.get("__constructor" /* Constructor */);
- if (!ctr) {
+ function findSuperConstructorAccesses(classDeclaration, addNode) {
+ var constructor = getClassConstructorSymbol(classDeclaration.symbol);
+ if (!constructor) {
return;
}
- for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) {
+ for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
ts.Debug.assert(decl.kind === 157 /* Constructor */);
var body = decl.body;
@@ -100774,6 +102741,16 @@
}
}
}
+ function hasOwnConstructor(classDeclaration) {
+ return !!getClassConstructorSymbol(classDeclaration.symbol);
+ }
+ function findInheritedConstructorReferences(classDeclaration, state) {
+ if (hasOwnConstructor(classDeclaration))
+ return;
+ var classSymbol = classDeclaration.symbol;
+ var search = state.createSearch(/*location*/ undefined, classSymbol, /*comingFrom*/ undefined);
+ getReferencesInContainerOrFiles(classSymbol, state, search);
+ }
function addImplementationReferences(refNode, addReference, state) {
// Check if we found a function/propertyAssignment/method with an implementation or initializer
if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) {
@@ -100938,7 +102915,7 @@
staticFlag &= ts.getModifierFlags(searchSpaceNode);
searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) {
return undefined;
}
@@ -100951,7 +102928,7 @@
default:
return undefined;
}
- var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
+ var references = ts.flatMap(searchSpaceNode.kind === 284 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) {
if (!ts.isThis(node)) {
@@ -100970,8 +102947,8 @@
// 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 279 /* SourceFile */:
- return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
+ case 284 /* SourceFile */:
+ return container.kind === 284 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
}
});
}).map(function (n) { return FindAllReferences.nodeEntry(n); });
@@ -101825,11 +103802,11 @@
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return [declaration];
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return [declaration, declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
@@ -101850,16 +103827,16 @@
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
var name = tag.name;
return name ? withNode(name) : comment;
default:
@@ -102070,7 +104047,7 @@
: undefined;
return { commentOwner: commentOwner, parameters: parameters_1 };
}
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return "quit";
case 244 /* ModuleDeclaration */:
// If in walking up the tree, we hit a a nested namespace declaration,
@@ -102630,7 +104607,7 @@
}
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
var sourceFile = node;
return ts.isExternalModule(sourceFile)
? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\""
@@ -102682,10 +104659,10 @@
case 243 /* EnumDeclaration */:
case 241 /* InterfaceDeclaration */:
case 244 /* ModuleDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 242 /* TypeAliasDeclaration */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return true;
case 157 /* Constructor */:
case 156 /* MethodDeclaration */:
@@ -102706,7 +104683,7 @@
}
switch (navigationBarNodeKind(item.parent)) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
return true;
@@ -102791,7 +104768,7 @@
return !member.name || member.name.kind === 149 /* ComputedPropertyName */;
}
function getNodeSpan(node) {
- return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
+ return node.kind === 284 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
}
function getModifiers(node) {
if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) {
@@ -102912,8 +104889,8 @@
else {
// Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: false,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include,
suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
});
}
@@ -102927,7 +104904,7 @@
function removeUnusedImports(oldImports, sourceFile, program) {
var typeChecker = program.getTypeChecker();
var jsxNamespace = typeChecker.getJsxNamespace(sourceFile);
- var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */);
+ var jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */);
var usedImports = [];
for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) {
var importDecl = oldImports_1[_i];
@@ -103638,7 +105615,7 @@
if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
return true;
}
- if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) {
+ if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 7 /* Latest */)) {
return false;
}
// TODO: find a way to determine this for any unicode characters in a
@@ -103651,7 +105628,7 @@
if (ch >= 97 /* a */ && ch <= 122 /* z */) {
return true;
}
- if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) {
+ if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 7 /* Latest */)) {
return false;
}
// TODO: find a way to determine this for any unicode characters in a
@@ -104768,13 +106745,13 @@
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); })));
+ var params = ts.createNodeArray(thisParameter.concat(checker.getExpandedParameters(candidateSignature).map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); })));
printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer);
});
return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) };
}
function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
- var isVariadic = candidateSignature.hasRestParameter;
+ var isVariadic = checker.hasEffectiveRestParameter(candidateSignature);
var printer = ts.createPrinter({ removeComments: true });
var typeParameterParts = ts.mapToDisplayParts(function (writer) {
if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) {
@@ -104782,7 +106759,7 @@
printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer);
}
});
- var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); });
+ var parameters = checker.getExpandedParameters(candidateSignature).map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); });
return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] };
}
function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) {
@@ -104971,8 +106948,8 @@
var name = importNameForConvertToDefaultImport(importNode);
if (!name)
continue;
- var module_1 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
- var resolvedFile = module_1 && program.getSourceFile(module_1.resolvedFileName);
+ var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
+ var resolvedFile = module && program.getSourceFile(module.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));
}
@@ -105425,7 +107402,7 @@
displayParts.push(ts.spacePart());
addFullSymbolName(symbol);
}
- if (symbolFlags & 1536 /* Module */) {
+ if (symbolFlags & 1536 /* Module */ && !isThisExpression) {
prefixNextMeaning();
var declaration = ts.getDeclarationOfKind(symbol, 244 /* ModuleDeclaration */);
var isNamespace = declaration && declaration.name && declaration.name.kind === 72 /* Identifier */;
@@ -105609,7 +107586,7 @@
// 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 === 279 /* SourceFile */; })) {
+ if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 284 /* SourceFile */; })) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) {
@@ -105734,7 +107711,7 @@
// 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 === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
+ if (parent.kind === 284 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
return false;
}
}
@@ -105963,8 +107940,8 @@
(function (ts) {
var formatting;
(function (formatting) {
- var standardScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
- var jsxScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */);
+ var standardScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
+ var jsxScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */);
var ScanAction;
(function (ScanAction) {
ScanAction[ScanAction["Scan"] = 0] = "Scan";
@@ -106558,7 +108535,7 @@
case 226 /* ForInStatement */:
// "in" keyword in [P in keyof T]: T[P]
case 150 /* TypeParameter */:
- return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */;
+ return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */ || context.currentTokenSpan.kind === 59 /* EqualsToken */ || context.nextTokenSpan.kind === 59 /* EqualsToken */;
// Technically, "of" is not a binary operator, but format it the same way as "in"
case 227 /* ForOfStatement */:
return context.currentTokenSpan.kind === 147 /* OfKeyword */ || context.nextTokenSpan.kind === 147 /* OfKeyword */;
@@ -107059,7 +109036,7 @@
case 244 /* ModuleDeclaration */:
var body = parent.body;
return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 245 /* ModuleBlock */:
return ts.rangeContainsRange(parent.statements, node);
@@ -108178,7 +110155,7 @@
// - 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 === 279 /* SourceFile */ || !parentAndChildShareLine);
+ (parent.kind === 284 /* SourceFile */ || !parentAndChildShareLine);
if (!useActualIndentation) {
return -1 /* Unknown */;
}
@@ -108266,7 +110243,7 @@
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return getList(node.typeParameters);
case 192 /* NewExpression */:
case 191 /* CallExpression */:
@@ -108515,11 +110492,23 @@
ts.Debug.assert(typeof end === "number");
n.__end = end;
}
- var Position;
- (function (Position) {
- Position[Position["FullStart"] = 0] = "FullStart";
- Position[Position["Start"] = 1] = "Start";
- })(Position = textChanges_3.Position || (textChanges_3.Position = {}));
+ var LeadingTriviaOption;
+ (function (LeadingTriviaOption) {
+ /** Exclude all leading trivia (use getStart()) */
+ LeadingTriviaOption[LeadingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include leading trivia and,
+ * if there are no line breaks between the node and the previous token,
+ * include all trivia between the node and the previous token
+ */
+ LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll";
+ })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {}));
+ var TrailingTriviaOption;
+ (function (TrailingTriviaOption) {
+ /** Exclude all trailing trivia (use getEnd()) */
+ TrailingTriviaOption[TrailingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include trailing trivia */
+ TrailingTriviaOption[TrailingTriviaOption["Include"] = 1] = "Include";
+ })(TrailingTriviaOption = textChanges_3.TrailingTriviaOption || (textChanges_3.TrailingTriviaOption = {}));
function skipWhitespacesAndLineBreaks(text, start) {
return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
@@ -108535,9 +110524,9 @@
}
return false;
}
- textChanges_3.useNonAdjustedPositions = {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: true,
+ var useNonAdjustedPositions = {
+ leadingTriviaOption: LeadingTriviaOption.Exclude,
+ trailingTriviaOption: TrailingTriviaOption.Exclude,
};
var ChangeKind;
(function (ChangeKind) {
@@ -108547,10 +110536,11 @@
ChangeKind[ChangeKind["Text"] = 3] = "Text";
})(ChangeKind || (ChangeKind = {}));
function getAdjustedRange(sourceFile, startNode, endNode, options) {
- return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) };
+ return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) };
}
- function getAdjustedStartPosition(sourceFile, node, options, position) {
- if (options.useNonAdjustedStartPosition) {
+ function getAdjustedStartPosition(sourceFile, node, options) {
+ var leadingTriviaOption = options.leadingTriviaOption;
+ if (leadingTriviaOption === LeadingTriviaOption.Exclude) {
return node.getStart(sourceFile);
}
var fullStart = node.getFullStart();
@@ -108568,7 +110558,7 @@
// fullstart
// when b is replaced - we usually want to keep the leading trvia
// when b is deleted - we delete it
- return position === Position.Start ? start : fullStart;
+ return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start;
}
// get start position of the line following the line that contains fullstart position
// (but only if the fullstart isn't the very beginning of the file)
@@ -108580,11 +110570,12 @@
}
function getAdjustedEndPosition(sourceFile, node, options) {
var end = node.end;
- if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
+ var trailingTriviaOption = options.trailingTriviaOption;
+ if (trailingTriviaOption === TrailingTriviaOption.Exclude || (ts.isExpression(node) && trailingTriviaOption !== TrailingTriviaOption.Include)) {
return end;
}
var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
- return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
+ return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)))
? newEnd
: end;
}
@@ -108629,15 +110620,15 @@
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 = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
- var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
+ var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
@@ -108645,11 +110636,11 @@
this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
};
ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
};
ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options);
};
ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
@@ -108657,14 +110648,14 @@
this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
};
ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
};
ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
- this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text);
+ this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text);
};
ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
@@ -108692,7 +110683,7 @@
};
ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) {
if (blankLineBetween === void 0) { blankLineBetween = false; }
- this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
+ this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
};
ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) {
var pos = before.getStart(sourceFile);
@@ -108799,7 +110790,7 @@
this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true));
};
ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) {
- var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start);
+ var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {});
this.insertNodeAt(sourceFile, pos, newNode, {
prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
suffix: this.newLineCharacter
@@ -109089,7 +111080,7 @@
textChanges_3.ChangeTracker = ChangeTracker;
// find first non-whitespace position in the leading trivia of the node
function startPositionToDeleteNodeInList(sourceFile, node) {
- return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
function getClassOrObjectBraceEnds(cls, sourceFile) {
return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end];
@@ -109133,7 +111124,7 @@
function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) {
// TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this
var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter);
- var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind);
+ var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 7 /* ESNext */, /*setParentNodes*/ true, scriptKind);
var changes = ts.formatting.formatDocument(sourceFile, formatContext);
return applyChanges(nonFormattedText, changes) + newLineCharacter;
}
@@ -109426,7 +111417,7 @@
case 249 /* ImportDeclaration */:
deleteNode(changes, sourceFile, node,
// For first import, leave header comment in place
- node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined);
+ node === sourceFile.imports[0].parent ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined);
break;
case 186 /* BindingElement */:
var pattern = node.parent;
@@ -109464,7 +111455,7 @@
deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
}
else {
- deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined);
+ deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { trailingTriviaOption: TrailingTriviaOption.Exclude } : undefined);
}
}
}
@@ -109535,8 +111526,8 @@
/** 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);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, node, options);
var endPosition = getAdjustedEndPosition(sourceFile, node, options);
changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
}
@@ -109829,18 +111820,18 @@
}
function transformJSDocType(node) {
switch (node.kind) {
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 164 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -109864,7 +111855,7 @@
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
+ var isRest = node.type.kind === 295 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
var name = node.name || (isRest ? "rest" : "arg" + index);
var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken;
return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
@@ -110020,7 +112011,7 @@
}
if (ts.isPropertyAccessExpression(parent)) {
var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken);
- var typeNode = getTypeNodeIfAccessible(type, parent, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host);
if (typeNode) {
// Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags
var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ "");
@@ -110124,7 +112115,7 @@
}
}
function annotate(changes, sourceFile, declaration, type, program, host) {
- var typeNode = getTypeNodeIfAccessible(type, declaration, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host);
if (typeNode) {
if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) {
var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration;
@@ -110150,7 +112141,7 @@
// only infer parameters that have (1) no type and (2) an accessible inferred type
if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name))
return;
- var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host);
+ var typeNode = inference.type && ts.getTypeNodeIfAccessible(inference.type, param, program, host);
var name = ts.getSynthesizedClone(param.name);
ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), "");
@@ -110167,47 +112158,33 @@
return !!merged;
}); });
var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray((oldTags || ts.emptyArray).concat(unmergedNewTags)));
- changes.insertJsdocCommentBefore(sourceFile, parent, tag);
+ var jsDocNode = parent.kind === 197 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent;
+ jsDocNode.jsDoc = parent.jsDoc;
+ jsDocNode.jsDocCache = parent.jsDocCache;
+ changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag);
+ }
+ function getJsDocNodeForArrowFunction(signature) {
+ if (signature.parent.kind === 154 /* PropertyDeclaration */) {
+ return signature.parent;
+ }
+ return signature.parent.parent;
}
function tryMergeJsdocTags(oldTag, newTag) {
if (oldTag.kind !== newTag.kind) {
return undefined;
}
switch (oldTag.kind) {
- case 299 /* JSDocParameterTag */: {
+ case 304 /* JSDocParameterTag */: {
var oldParam = oldTag;
var newParam = newTag;
return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText
? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment)
: undefined;
}
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment);
}
}
- function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
- var checker = program.getTypeChecker();
- var typeIsAccessible = true;
- var notAccessible = function () { typeIsAccessible = false; };
- var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
- trackSymbol: function (symbol, declaration, meaning) {
- // TODO: GH#18217
- typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
- },
- reportInaccessibleThisError: notAccessible,
- reportPrivateInBaseOfClassExpression: notAccessible,
- reportInaccessibleUniqueSymbolError: notAccessible,
- moduleResolverHost: {
- readFile: host.readFile,
- fileExists: host.fileExists,
- directoryExists: host.directoryExists,
- getSourceFiles: program.getSourceFiles,
- getCurrentDirectory: program.getCurrentDirectory,
- getCommonSourceDirectory: program.getCommonSourceDirectory,
- }
- });
- return typeIsAccessible ? res : undefined;
- }
function getReferences(token, program, cancellationToken) {
// Position shouldn't matter since token is not a SourceFile.
return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) {
@@ -110720,7 +112697,7 @@
precedingNode = ctorDeclaration.parent.parent;
newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
if (ctorDeclaration.parent.declarations.length === 1) {
- ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
+ ts.copyLeadingComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
changes.delete(sourceFile, precedingNode);
}
else {
@@ -110731,7 +112708,7 @@
if (!newClassDeclaration) {
return undefined;
}
- ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile);
+ ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile);
// Because the preceding node could be touched, we need to insert nodes before delete nodes.
changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
function createClassElementsFromSymbol(symbol) {
@@ -110784,7 +112761,7 @@
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
case 197 /* ArrowFunction */: {
@@ -110802,7 +112779,7 @@
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
default: {
@@ -110812,7 +112789,7 @@
}
var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
/*type*/ undefined, assignmentBinaryExpression.right);
- ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
return prop;
}
}
@@ -113561,7 +115538,7 @@
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 === 286 /* JSDocNullableType */) {
+ if (typeNode.kind === 291 /* 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, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -113581,7 +115558,7 @@
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 291 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -113878,7 +115855,7 @@
ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined;
});
var contextualType = checker.getContextualType(call);
- var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker) || ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ var returnType = (inJs || !contextualType) ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker);
return ts.createMethod(
/*decorators*/ undefined,
/*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined,
@@ -114213,6 +116190,7 @@
return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings));
}
ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText;
+ /* @internal */
var OutputKind;
(function (OutputKind) {
OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals";
@@ -114347,7 +116325,7 @@
}
}
function toPropertyName(name) {
- return ts.isIdentifierText(name, 6 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name);
+ return ts.isIdentifierText(name, 7 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name);
}
// Parses assignments to "this.x" in the constructor into class property declarations
function getConstructorFunctionInstanceProperties(fnAst, members) {
@@ -114391,7 +116369,7 @@
}
function parseExpression(expr) {
var text = "const _ = " + expr;
- var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true);
+ var srcFile = ts.createSourceFile("test.ts", text, 7 /* Latest */, /*setParentNodes*/ true);
return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer;
}
function inferParameterType(_fn, _param) {
@@ -114408,7 +116386,7 @@
}
function isValidIdentifier(name) {
var keyword = ts.stringToToken(name);
- return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */);
+ return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 7 /* ESNext */);
}
function addComment(node, comment) {
if (comment !== undefined)
@@ -114863,7 +116841,7 @@
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 preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 7 /* 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);
@@ -115380,7 +117358,7 @@
// * Module/namespace or source file
if (isScope(current)) {
scopes.push(current);
- if (current.kind === 279 /* SourceFile */) {
+ if (current.kind === 284 /* SourceFile */) {
return scopes;
}
}
@@ -116394,7 +118372,7 @@
function isBlockLike(node) {
switch (node.kind) {
case 218 /* Block */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 245 /* ModuleBlock */:
case 271 /* CaseClause */:
return true;
@@ -116758,7 +118736,7 @@
}
}
function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) {
- var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */);
+ var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 7 /* ESNext */);
var needUniqueName = false;
var toChange = [];
ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) {
@@ -116856,9 +118834,9 @@
if (isTopLevelDeclarationStatement(statement) &&
!isExported(sourceFile, statement, useEs6Exports) &&
forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) {
- var exports_1 = addExport(statement, useEs6Exports);
- if (exports_1)
- return exports_1;
+ var exports = addExport(statement, useEs6Exports);
+ if (exports)
+ return exports;
}
return statement;
});
@@ -116984,7 +118962,7 @@
var movedSymbols = new SymbolSet();
var oldImportsNeededByNewFile = new SymbolSet();
var newFileImportsFromOldFile = new SymbolSet();
- var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 4 /* ContainsJsx */); });
+ var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 2 /* ContainsJsx */); });
var jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx);
if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code)
oldImportsNeededByNewFile.add(jsxNamespaceSymbol);
@@ -117018,7 +118996,7 @@
if (ts.contains(toMove, statement))
continue;
// jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile.
- if (jsxNamespaceSymbol && !!(statement.transformFlags & 4 /* ContainsJsx */)) {
+ if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) {
unusedImportsFromOldFile.delete(jsxNamespaceSymbol);
}
forEachReference(statement, checker, function (symbol) {
@@ -117333,13 +119311,13 @@
var returnStatement_1 = ts.createReturn(expression);
body = ts.createBlock([returnStatement_1], /* multiLine */ true);
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
+ ts.copyLeadingComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
}
else if (actionName === removeBracesActionName && returnStatement) {
var actualExpression = expression || ts.createVoidZero();
body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression;
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
+ ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
}
else {
ts.Debug.fail("invalid action");
@@ -117378,6 +119356,459 @@
})(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var convertParamsToDestructuredObject;
+ (function (convertParamsToDestructuredObject) {
+ var refactorName = "Convert parameters to destructured object";
+ var minimumParameterLength = 2;
+ refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
+ function getAvailableActions(context) {
+ var file = context.file, startPosition = context.startPosition;
+ var isJSFile = ts.isSourceFileJS(file);
+ if (isJSFile)
+ return ts.emptyArray; // TODO: GH#30113
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
+ if (!functionDeclaration)
+ return ts.emptyArray;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_parameters_to_destructured_object);
+ return [{
+ name: refactorName,
+ description: description,
+ actions: [{
+ name: refactorName,
+ description: description
+ }]
+ }];
+ }
+ function getEditsForAction(context, actionName) {
+ ts.Debug.assert(actionName === refactorName);
+ var file = context.file, startPosition = context.startPosition, program = context.program, cancellationToken = context.cancellationToken, host = context.host;
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker());
+ if (!functionDeclaration || !cancellationToken)
+ return undefined;
+ var groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken);
+ if (groupedReferences.valid) {
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(file, program, host, t, functionDeclaration, groupedReferences); });
+ return { renameFilename: undefined, renameLocation: undefined, edits: edits };
+ }
+ return { edits: [] }; // TODO: GH#30113
+ }
+ function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) {
+ var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); });
+ changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ",
+ // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
+ indentation: 0,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include
+ });
+ var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); });
+ for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) {
+ var call = functionCalls_1[_i];
+ if (call.arguments && call.arguments.length) {
+ var newArgument = ts.getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true);
+ changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include });
+ }
+ }
+ }
+ function getGroupedReferences(functionDeclaration, program, cancellationToken) {
+ var functionNames = getFunctionNames(functionDeclaration);
+ var classNames = ts.isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
+ var names = ts.deduplicate(functionNames.concat(classNames), ts.equateValues);
+ var checker = program.getTypeChecker();
+ var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); });
+ var groupedReferences = groupReferences(references);
+ if (!ts.every(groupedReferences.declarations, /*callback*/ function (/*callback*/ decl) { return ts.contains(names, decl); })) {
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ function groupReferences(referenceEntries) {
+ var classReferences = { accessExpressions: [], typeUsages: [] };
+ var groupedReferences = { functionCalls: [], declarations: [], classReferences: classReferences, valid: true };
+ var functionSymbols = ts.map(functionNames, checker.getSymbolAtLocation);
+ var classSymbols = ts.map(classNames, checker.getSymbolAtLocation);
+ var isConstructor = ts.isConstructorDeclaration(functionDeclaration);
+ for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
+ var entry = referenceEntries_1[_i];
+ if (entry.kind !== 1 /* Node */) {
+ groupedReferences.valid = false;
+ continue;
+ }
+ /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function.
+ Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test:
+ class A { foo(a: number, b: number) { return a + b; } }
+ class B { foo(c: number, d: number) { return c + d; } }
+ declare const ab: A | B;
+ ab.foo(1, 2);
+ Find all references will return `ab.foo(1, 2)` as a reference to A's `foo` but we could be calling B's `foo`.
+ When looking for constructor calls, however, the symbol on the constructor call reference is going to be the corresponding class symbol.
+ So we need to add a special case for this because when calling a constructor of a class through one of its subclasses,
+ the symbols are going to be different.
+ */
+ if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer) || ts.isNewExpressionTarget(entry.node)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var call = entryToFunctionCall(entry);
+ if (call) {
+ groupedReferences.functionCalls.push(call);
+ continue;
+ }
+ }
+ // if the refactored function is a constructor, we must also check if the references to its class are valid
+ if (isConstructor && ts.contains(classSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var accessExpression = entryToAccessExpression(entry);
+ if (accessExpression) {
+ classReferences.accessExpressions.push(accessExpression);
+ continue;
+ }
+ // Only class declarations are allowed to be used as a type (in a heritage clause),
+ // otherwise `findAllReferences` might not be able to track constructor calls.
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ var type = entryToType(entry);
+ if (type) {
+ classReferences.typeUsages.push(type);
+ continue;
+ }
+ }
+ }
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ }
+ }
+ function symbolComparer(a, b) {
+ return ts.getSymbolTarget(a) === ts.getSymbolTarget(b);
+ }
+ function entryToDeclaration(entry) {
+ if (ts.isDeclaration(entry.node.parent)) {
+ return entry.node;
+ }
+ return undefined;
+ }
+ function entryToFunctionCall(entry) {
+ if (entry.node.parent) {
+ var functionReference = entry.node;
+ var parent = functionReference.parent;
+ switch (parent.kind) {
+ // Function call (foo(...) or super(...))
+ case 191 /* CallExpression */:
+ var callExpression = ts.tryCast(parent, ts.isCallExpression);
+ if (callExpression && callExpression.expression === functionReference) {
+ return callExpression;
+ }
+ break;
+ // Constructor call (new Foo(...))
+ case 192 /* NewExpression */:
+ var newExpression = ts.tryCast(parent, ts.isNewExpression);
+ if (newExpression && newExpression.expression === functionReference) {
+ return newExpression;
+ }
+ break;
+ // Method call (x.foo(...))
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) {
+ var callExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_1 && callExpression_1.expression === propertyAccessExpression) {
+ return callExpression_1;
+ }
+ }
+ break;
+ // Method call (x["foo"](...))
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) {
+ var callExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_2 && callExpression_2.expression === elementAccessExpression) {
+ return callExpression_2;
+ }
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToAccessExpression(entry) {
+ if (entry.node.parent) {
+ var reference = entry.node;
+ var parent = reference.parent;
+ switch (parent.kind) {
+ // `C.foo`
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.expression === reference) {
+ return propertyAccessExpression;
+ }
+ break;
+ // `C["foo"]`
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.expression === reference) {
+ return elementAccessExpression;
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToType(entry) {
+ var reference = entry.node;
+ if (ts.getMeaningFromLocation(reference) === 2 /* Type */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) {
+ return reference;
+ }
+ return undefined;
+ }
+ function getFunctionDeclarationAtPosition(file, startPosition, checker) {
+ var node = ts.getTouchingToken(file, startPosition);
+ var functionDeclaration = ts.getContainingFunction(node);
+ // don't offer refactor on top-level JSDoc
+ if (isTopLevelJSDoc(node))
+ return undefined;
+ if (functionDeclaration
+ && isValidFunctionDeclaration(functionDeclaration, checker)
+ && ts.rangeContainsRange(functionDeclaration, node)
+ && !(functionDeclaration.body && ts.rangeContainsRange(functionDeclaration.body, node)))
+ return functionDeclaration;
+ return undefined;
+ }
+ function isTopLevelJSDoc(node) {
+ var containingJSDoc = ts.findAncestor(node, ts.isJSDocNode);
+ if (containingJSDoc) {
+ var containingNonJSDoc = ts.findAncestor(containingJSDoc, function (n) { return !ts.isJSDocNode(n); });
+ return !!containingNonJSDoc && ts.isFunctionLikeDeclaration(containingNonJSDoc);
+ }
+ return false;
+ }
+ function isValidFunctionDeclaration(functionDeclaration, checker) {
+ if (!isValidParameterNodeArray(functionDeclaration.parameters, checker))
+ return false;
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return !!functionDeclaration.name
+ && !!functionDeclaration.body
+ && !checker.isImplementationOfOverload(functionDeclaration);
+ case 157 /* Constructor */:
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ return !!functionDeclaration.body
+ && !!functionDeclaration.parent.name
+ && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ else {
+ return isValidVariableDeclaration(functionDeclaration.parent.parent)
+ && !!functionDeclaration.body
+ && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ case 196 /* FunctionExpression */:
+ case 197 /* ArrowFunction */:
+ return isValidVariableDeclaration(functionDeclaration.parent);
+ }
+ return false;
+ }
+ function isValidParameterNodeArray(parameters, checker) {
+ return getRefactorableParametersLength(parameters) >= minimumParameterLength
+ && ts.every(parameters, /*callback*/ function (/*callback*/ paramDecl) { return isValidParameterDeclaration(paramDecl, checker); });
+ }
+ function isValidParameterDeclaration(parameterDeclaration, checker) {
+ if (ts.isRestParameter(parameterDeclaration)) {
+ var type = checker.getTypeAtLocation(parameterDeclaration);
+ if (!checker.isArrayType(type) && !checker.isTupleType(type))
+ return false;
+ }
+ return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name);
+ }
+ function isValidVariableDeclaration(node) {
+ return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113
+ }
+ function hasThisParameter(parameters) {
+ return parameters.length > 0 && ts.isThis(parameters[0].name);
+ }
+ function getRefactorableParametersLength(parameters) {
+ if (hasThisParameter(parameters)) {
+ return parameters.length - 1;
+ }
+ return parameters.length;
+ }
+ function getRefactorableParameters(parameters) {
+ if (hasThisParameter(parameters)) {
+ parameters = ts.createNodeArray(parameters.slice(1), parameters.hasTrailingComma);
+ }
+ return parameters;
+ }
+ function createPropertyOrShorthandAssignment(name, initializer) {
+ if (ts.isIdentifier(initializer) && ts.getTextOfIdentifierOrLiteral(initializer) === name) {
+ return ts.createShorthandPropertyAssignment(name);
+ }
+ return ts.createPropertyAssignment(name, initializer);
+ }
+ function createNewArgument(functionDeclaration, functionArguments) {
+ var parameters = getRefactorableParameters(functionDeclaration.parameters);
+ var hasRestParameter = ts.isRestParameter(ts.last(parameters));
+ var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments;
+ var properties = ts.map(nonRestArguments, function (arg, i) {
+ var parameterName = getParameterName(parameters[i]);
+ var property = createPropertyOrShorthandAssignment(parameterName, arg);
+ ts.suppressLeadingAndTrailingTrivia(property.name);
+ if (ts.isPropertyAssignment(property))
+ ts.suppressLeadingAndTrailingTrivia(property.initializer);
+ copyComments(arg, property);
+ return property;
+ });
+ if (hasRestParameter && functionArguments.length >= parameters.length) {
+ var restArguments = functionArguments.slice(parameters.length - 1);
+ var restProperty = ts.createPropertyAssignment(getParameterName(ts.last(parameters)), ts.createArrayLiteral(restArguments));
+ properties.push(restProperty);
+ }
+ var objectLiteral = ts.createObjectLiteral(properties, /*multiLine*/ false);
+ return objectLiteral;
+ }
+ function createNewParameters(functionDeclaration, program, host) {
+ var checker = program.getTypeChecker();
+ var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters);
+ var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration);
+ var objectParameterName = ts.createObjectBindingPattern(bindingElements);
+ var objectParameterType = createParameterTypeNode(refactorableParameters);
+ var objectInitializer;
+ // If every parameter in the original function was optional, add an empty object initializer to the new object parameter
+ if (ts.every(refactorableParameters, isOptionalParameter)) {
+ objectInitializer = ts.createObjectLiteral();
+ }
+ var objectParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, objectParameterName,
+ /*questionToken*/ undefined, objectParameterType, objectInitializer);
+ if (hasThisParameter(functionDeclaration.parameters)) {
+ var thisParameter = functionDeclaration.parameters[0];
+ var newThisParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, thisParameter.name,
+ /*questionToken*/ undefined, thisParameter.type);
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.name);
+ copyComments(thisParameter.name, newThisParameter.name);
+ if (thisParameter.type) {
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.type);
+ copyComments(thisParameter.type, newThisParameter.type);
+ }
+ return ts.createNodeArray([newThisParameter, objectParameter]);
+ }
+ return ts.createNodeArray([objectParameter]);
+ function createBindingElementFromParameterDeclaration(parameterDeclaration) {
+ var element = ts.createBindingElement(
+ /*dotDotDotToken*/ undefined,
+ /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer);
+ ts.suppressLeadingAndTrailingTrivia(element);
+ if (parameterDeclaration.initializer && element.initializer) {
+ copyComments(parameterDeclaration.initializer, element.initializer);
+ }
+ return element;
+ }
+ function createParameterTypeNode(parameters) {
+ var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration);
+ var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */);
+ return typeNode;
+ }
+ function createPropertySignatureFromParameterDeclaration(parameterDeclaration) {
+ var parameterType = parameterDeclaration.type;
+ if (!parameterType && (parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration))) {
+ parameterType = getTypeNode(parameterDeclaration);
+ }
+ var propertySignature = ts.createPropertySignature(
+ /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType,
+ /*initializer*/ undefined);
+ ts.suppressLeadingAndTrailingTrivia(propertySignature);
+ copyComments(parameterDeclaration.name, propertySignature.name);
+ if (parameterDeclaration.type && propertySignature.type) {
+ copyComments(parameterDeclaration.type, propertySignature.type);
+ }
+ return propertySignature;
+ }
+ function getTypeNode(node) {
+ var type = checker.getTypeAtLocation(node);
+ return ts.getTypeNodeIfAccessible(type, node, program, host);
+ }
+ function isOptionalParameter(parameterDeclaration) {
+ if (ts.isRestParameter(parameterDeclaration)) {
+ var type = checker.getTypeAtLocation(parameterDeclaration);
+ return !checker.isTupleType(type);
+ }
+ return checker.isOptionalParameter(parameterDeclaration);
+ }
+ }
+ function copyComments(sourceNode, targetNode) {
+ var sourceFile = sourceNode.getSourceFile();
+ var text = sourceFile.text;
+ if (hasLeadingLineBreak(sourceNode, text)) {
+ ts.copyLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ else {
+ ts.copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ ts.copyTrailingComments(sourceNode, targetNode, sourceFile);
+ }
+ function hasLeadingLineBreak(node, text) {
+ var start = node.getFullStart();
+ var end = node.getStart();
+ for (var i = start; i < end; i++) {
+ if (text.charCodeAt(i) === 10 /* lineFeed */)
+ return true;
+ }
+ return false;
+ }
+ function getParameterName(paramDeclaration) {
+ return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name);
+ }
+ function getClassNames(constructorDeclaration) {
+ switch (constructorDeclaration.parent.kind) {
+ case 240 /* ClassDeclaration */:
+ var classDeclaration = constructorDeclaration.parent;
+ return [classDeclaration.name];
+ case 209 /* ClassExpression */:
+ var classExpression = constructorDeclaration.parent;
+ var variableDeclaration = constructorDeclaration.parent.parent;
+ var className = classExpression.name;
+ if (className)
+ return [className, variableDeclaration.name];
+ return [variableDeclaration.name];
+ }
+ }
+ function getFunctionNames(functionDeclaration) {
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return [functionDeclaration.name];
+ case 157 /* Constructor */:
+ var ctrKeyword = ts.findChildOfKind(functionDeclaration, 124 /* ConstructorKeyword */, functionDeclaration.getSourceFile());
+ if (functionDeclaration.parent.kind === 209 /* ClassExpression */) {
+ var variableDeclaration = functionDeclaration.parent.parent;
+ return [variableDeclaration.name, ctrKeyword];
+ }
+ return [ctrKeyword];
+ case 197 /* ArrowFunction */:
+ return [functionDeclaration.parent.name];
+ case 196 /* FunctionExpression */:
+ if (functionDeclaration.name)
+ return [functionDeclaration.name, functionDeclaration.parent.name];
+ return [functionDeclaration.parent.name];
+ default:
+ return ts.Debug.assertNever(functionDeclaration);
+ }
+ }
+ })(convertParamsToDestructuredObject = refactor.convertParamsToDestructuredObject || (refactor.convertParamsToDestructuredObject = {}));
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
var ts;
(function (ts) {
/** The version of the language service API */
@@ -117395,7 +119826,8 @@
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
- this.transformFlags = undefined; // TODO: GH#18217
+ this.modifierFlagsCache = 0 /* None */;
+ this.transformFlags = 0 /* None */;
this.parent = undefined;
this.kind = kind;
}
@@ -117457,7 +119889,7 @@
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 288 /* FirstJSDocNode */ || kid.kind > 310 /* LastJSDocNode */; });
return child.kind < 148 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -117527,7 +119959,7 @@
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(311 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
@@ -117545,6 +119977,8 @@
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
+ this.modifierFlagsCache = 0 /* None */;
+ this.transformFlags = 0 /* None */;
this.parent = undefined;
}
TokenOrIdentifierObject.prototype.getSourceFile = function () {
@@ -118120,7 +120554,7 @@
var sourceFile;
if (this.currentFileName !== fileName) {
// This is a new file, just parse it
- sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 6 /* Latest */, version, /*setNodeParents*/ true, scriptKind);
+ sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 7 /* Latest */, version, /*setNodeParents*/ true, scriptKind);
}
else if (this.currentFileVersion !== version) {
// This is the same file, just a newer version. Incrementally parse the file.
@@ -118244,9 +120678,9 @@
}());
ts.ThrottledCancellationToken = ThrottledCancellationToken;
function createLanguageService(host, documentRegistry, syntaxOnly) {
+ var _a;
if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); }
if (syntaxOnly === void 0) { syntaxOnly = false; }
- var _a;
var syntaxTreeCache = new SyntaxTreeCache(host);
var program;
var lastProjectVersion;
@@ -118277,7 +120711,7 @@
function getValidSourceFile(fileName) {
var sourceFile = program.getSourceFile(fileName);
if (!sourceFile) {
- throw new Error("Could not find file: '" + fileName + "'.");
+ throw new Error("Could not find sourceFile: '" + fileName + "' in " + (program && JSON.stringify(program.getSourceFiles().map(function (f) { return f.fileName; }))) + ".");
}
return sourceFile;
}
@@ -120644,8 +123078,6 @@
// TODO: it should be moved into a namespace though.
/* @internal */
var toolsVersion = ts.versionMajorMinor;
-//# sourceMappingURL=services.js.map
-"use strict";
/* @internal */
var ts;
(function (ts) {
@@ -120672,6 +123104,11 @@
* typingsInstaller will run the command with `${npmLocation} install ...`.
*/
Arguments.NpmLocation = "--npmLocation";
+ /**
+ * Flag indicating that the typings installer should try to validate the default npm location.
+ * If the default npm is not found when this flag is enabled, fallback to `npm install`
+ */
+ Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
})(Arguments = server.Arguments || (server.Arguments = {}));
function hasArgument(argumentName) {
return ts.sys.args.indexOf(argumentName) >= 0;
@@ -120986,41 +123423,6 @@
JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
})(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
})(ts || (ts = {}));
-//# sourceMappingURL=jsTyping.js.map
-"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];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-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 __rest = (this && this.__rest) || function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
- t[p[i]] = s[p[i]];
- return t;
-};
var ts;
(function (ts) {
var server;
@@ -121033,6 +123435,7 @@
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";
@@ -121042,7 +123445,7 @@
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,
@@ -121099,6 +123502,7 @@
}
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;
@@ -121107,25 +123511,34 @@
}
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" : ""));
@@ -121141,7 +123554,7 @@
return ThrottledOperations;
}());
server.ThrottledOperations = ThrottledOperations;
- var GcTimer = (function () {
+ var GcTimer = /** @class */ (function () {
function GcTimer(host, delay, logger) {
this.host = host;
this.delay = delay;
@@ -121149,6 +123562,7 @@
}
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);
@@ -121156,10 +123570,10 @@
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);
}
};
@@ -121190,13 +123604,16 @@
return indentStr + str.replace(/\n/g, indentStr);
}
server.indent = indent;
+ /** Put stringified JSON on the next line, indented. */
function stringifyIndented(json) {
return indentStr + JSON.stringify(json);
}
server.stringifyIndented = stringifyIndented;
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
+/* @internal */
(function (ts) {
+ // Additional tsserver specific watch information
var WatchType;
(function (WatchType) {
WatchType["ClosedScriptInfo"] = "Closed Script info";
@@ -121205,41 +123622,57 @@
WatchType["MissingSourceMapFile"] = "Missing source map file";
})(WatchType = ts.WatchType || (ts.WatchType = {}));
})(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";
@@ -121247,25 +123680,34 @@
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";
@@ -121275,33 +123717,48 @@
CommandTypes["OpenExternalProject"] = "openExternalProject";
CommandTypes["OpenExternalProjects"] = "openExternalProjects";
CommandTypes["CloseExternalProject"] = "closeExternalProject";
+ /* @internal */
CommandTypes["SynchronizeProjectList"] = "synchronizeProjectList";
+ /* @internal */
CommandTypes["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles";
+ CommandTypes["UpdateOpen"] = "updateOpen";
+ /* @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";
CommandTypes["ConfigurePlugin"] = "configurePlugin";
+ // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`.
})(CommandTypes = protocol.CommandTypes || (protocol.CommandTypes = {}));
var IndentStyle;
(function (IndentStyle) {
@@ -121354,13 +123811,23 @@
(function (ts) {
var server;
(function (server) {
- var TextStorage = (function () {
+ /* @internal */
+ var TextStorage = /** @class */ (function () {
function TextStorage(host, fileName, initialVersion, info) {
this.host = host;
this.fileName = fileName;
this.info = info;
+ /**
+ * True if the text is for the file thats open in the editor
+ */
this.isOpen = false;
+ /**
+ * True if the text present is the text from the file on the disk
+ */
this.ownFileText = false;
+ /**
+ * True when reloading contents of file from the disk is pending
+ */
this.pendingReloadFromDisk = false;
this.version = initialVersion || { svc: 0, text: 0 };
}
@@ -121383,6 +123850,7 @@
this.info.sourceInfos = undefined;
this.info.documentPositionMapper = undefined;
};
+ /** Public for testing */
TextStorage.prototype.useText = function (newText) {
this.svc = undefined;
this.text = newText;
@@ -121399,23 +123867,42 @@
this.fileSize = undefined;
this.resetSourceMapInfo();
};
+ /**
+ * 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;
}
return false;
};
+ /**
+ * 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 _a = this.getFileTextAndSize(tempFileName), newText = _a.text, fileSize = _a.fileSize;
var reloaded = this.reload(newText);
- this.fileSize = fileSize;
+ this.fileSize = fileSize; // NB: after reload since reload clears it
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();
@@ -121425,14 +123912,21 @@
TextStorage.prototype.delayReloadFromFileIntoText = function () {
this.pendingReloadFromDisk = true;
};
+ /**
+ * For telemetry purposes, we would like to be able to report the size of the file.
+ * However, we do not want telemetry to require extra file I/O so we report a size
+ * that may be stale (e.g. may not reflect change made on disk since the last reload).
+ * NB: Will read from disk if the file contents have never been loaded because
+ * telemetry falsely indicating size 0 would be counter-productive.
+ */
TextStorage.prototype.getTelemetryFileSize = function () {
return !!this.fileSize
? this.fileSize
- : !!this.text
- ? this.text.length
+ : !!this.text // Check text before svc because its length is cheaper
+ ? this.text.length // Could be wrong if this.pendingReloadFromDisk
: !!this.svc
- ? this.svc.getSnapshot().getLength()
- : this.getSnapshot().getLength();
+ ? this.svc.getSnapshot().getLength() // Could be wrong if this.pendingReloadFromDisk
+ : this.getSnapshot().getLength(); // Should be strictly correct
};
TextStorage.prototype.getSnapshot = function () {
return this.useScriptVersionCacheIfValidOrOpen()
@@ -121442,19 +123936,27 @@
TextStorage.prototype.getAbsolutePositionAndLineText = function (line) {
return this.switchToScriptVersionCache().getAbsolutePositionAndLineText(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, allowEdits) {
if (!this.useScriptVersionCacheIfValidOrOpen()) {
return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text, allowEdits);
}
+ // TODO: assert this offset is actually on the line
return this.svc.lineOffsetToPosition(line, offset);
};
TextStorage.prototype.positionToLineOffset = function (position) {
@@ -121469,6 +123971,7 @@
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.hasTSFileExtension(this.fileName)) {
var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length;
if (fileSize > server.maxFileSize) {
@@ -121489,12 +123992,15 @@
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 () {
@@ -121522,17 +124028,21 @@
return TextStorage;
}());
server.TextStorage = TextStorage;
+ /*@internal*/
function isDynamicFileName(fileName) {
return fileName[0] === "^" || ts.getBaseFileName(fileName)[0] === "^";
}
server.isDynamicFileName = isDynamicFileName;
- var ScriptInfo = (function () {
+ 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, initialVersion, this);
@@ -121544,12 +124054,15 @@
? scriptKind
: ts.getScriptKindFromFileName(fileName);
}
+ /*@internal*/
ScriptInfo.prototype.getVersion = function () {
return this.textStorage.version;
};
+ /*@internal*/
ScriptInfo.prototype.getTelemetryFileSize = function () {
return this.textStorage.getTelemetryFileSize();
};
+ /*@internal*/
ScriptInfo.prototype.isDynamicOrHasMixedContent = function () {
return this.hasMixedContent || this.isDynamic;
};
@@ -121560,6 +124073,7 @@
this.textStorage.isOpen = true;
if (newText !== undefined &&
this.textStorage.reload(newText)) {
+ // reload new contents only if the existing contents changed
this.markContainingProjectsAsDirty();
}
};
@@ -121580,6 +124094,7 @@
};
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);
@@ -121587,13 +124102,15 @@
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;
};
@@ -121611,6 +124128,7 @@
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;
@@ -121619,6 +124137,7 @@
}
};
ScriptInfo.prototype.detachFromProject = function (project) {
+ // unrolled for common cases
switch (this.containingProjects.length) {
case 0:
return;
@@ -121652,7 +124171,10 @@
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);
}
@@ -121666,6 +124188,9 @@
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];
@@ -121708,6 +124233,7 @@
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();
@@ -121727,6 +124253,7 @@
}
return false;
};
+ /*@internal*/
ScriptInfo.prototype.getAbsolutePositionAndLineText = function (line) {
return this.textStorage.getAbsolutePositionAndLineText(line);
};
@@ -121743,6 +124270,9 @@
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);
};
@@ -121753,11 +124283,13 @@
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 */;
};
+ /*@internal*/
ScriptInfo.prototype.getLineInfo = function () {
return this.textStorage.getLineInfo();
};
+ /*@internal*/
ScriptInfo.prototype.closeSourceMapFileWatcher = function () {
if (this.sourceMapFilePath && !ts.isString(this.sourceMapFilePath)) {
ts.closeFileWatcherOf(this.sourceMapFilePath);
@@ -121775,12 +124307,13 @@
(function (server) {
server.nullTypingsInstaller = {
isKnownTypesPackageName: ts.returnFalse,
+ // Should never be called because we never provide a types registry.
installPackage: ts.notImplemented,
inspectValue: 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) {
@@ -121817,6 +124350,7 @@
!setIsEqualTo(opt1.exclude, opt2.exclude);
}
function compilerOptionsChanged(opt1, opt2) {
+ // TODO: add more relevant properties
return opt1.allowJs !== opt2.allowJs;
}
function unresolvedImportsChanged(imports1, imports2) {
@@ -121825,7 +124359,8 @@
}
return !ts.arrayIsEqualTo(imports1, imports2);
}
- var TypingsCache = (function () {
+ /*@internal*/
+ var TypingsCache = /** @class */ (function () {
function TypingsCache(installer) {
this.installer = installer;
this.perProjectCache = ts.createMap();
@@ -121850,6 +124385,8 @@
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,
@@ -121857,6 +124394,7 @@
unresolvedImports: unresolvedImports,
poisoned: true
});
+ // something has been changed, issue a request to update typings
this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
}
};
@@ -121890,6 +124428,7 @@
ProjectKind[ProjectKind["Configured"] = 1] = "Configured";
ProjectKind[ProjectKind["External"] = 2] = "External";
})(ProjectKind = server.ProjectKind || (server.ProjectKind = {}));
+ /* @internal */
function countEachFileTypes(infos, includeSizes) {
if (includeSizes === void 0) { includeSizes = false; }
var result = {
@@ -121904,16 +124443,16 @@
var info = infos_1[_i];
var fileSize = includeSizes ? info.getTelemetryFileSize() : 0;
switch (info.scriptKind) {
- case 1:
+ case 1 /* JS */:
result.js += 1;
result.jsSize += fileSize;
break;
- case 2:
+ case 2 /* JSX */:
result.jsx += 1;
result.jsxSize += fileSize;
break;
- case 3:
- if (ts.fileExtensionIs(info.fileName, ".d.ts")) {
+ case 3 /* TS */:
+ if (ts.fileExtensionIs(info.fileName, ".d.ts" /* Dts */)) {
result.dts += 1;
result.dtsSize += fileSize;
}
@@ -121922,11 +124461,11 @@
result.tsSize += fileSize;
}
break;
- case 4:
+ case 4 /* TSX */:
result.tsx += 1;
result.tsxSize += fileSize;
break;
- case 7:
+ case 7 /* Deferred */:
result.deferred += 1;
result.deferredSize += fileSize;
break;
@@ -121949,16 +124488,20 @@
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;
@@ -121969,14 +124512,37 @@
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;
this.isInitialLoadPending = ts.returnFalse;
+ /*@internal*/
this.dirty = false;
+ /*@internal*/
this.hasChangedAutomaticTypeDirectiveNames = false;
+ /*@internal*/
this.typingFiles = server.emptyArray;
this.directoryStructureHost = directoryStructureHost;
this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || "");
@@ -121988,6 +124554,7 @@
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;
@@ -122002,7 +124569,8 @@
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);
@@ -122021,7 +124589,7 @@
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);
@@ -122035,6 +124603,7 @@
Project.prototype.installPackage = function (options) {
return this.typingsCache.installPackage(__assign({}, options, { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) }));
};
+ /* @internal */
Project.prototype.inspectValue = function (options) {
return this.typingsCache.inspectValue(options);
};
@@ -122045,9 +124614,11 @@
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();
};
@@ -122068,6 +124639,7 @@
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);
}
});
@@ -122078,6 +124650,7 @@
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);
}
@@ -122087,11 +124660,11 @@
};
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);
@@ -122122,6 +124695,8 @@
return this.projectService.host.writeFile(fileName, content);
};
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);
};
@@ -122135,33 +124710,41 @@
return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference);
};
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, "Failed Lookup Locations", this);
+ return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Failed Lookup Locations" /* FailedLookupLocations */, 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 roots", this);
+ return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Type roots" /* 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);
};
@@ -122176,6 +124759,9 @@
this.compilerOptions.noEmitForJsFiles = true;
}
};
+ /**
+ * Get the errors that dont have any file name associated
+ */
Project.prototype.getGlobalProjectErrors = function () {
return server.emptyArray;
};
@@ -122189,12 +124775,15 @@
}
return this.languageService;
};
+ /** @internal */
Project.prototype.getSourceMapper = function () {
return this.getLanguageService().getSourceMapper();
};
+ /*@internal*/
Project.prototype.getDocumentPositionMapper = function (generatedFileName, sourceFileName) {
return this.projectService.getDocumentPositionMapper(this, generatedFileName, sourceFileName);
};
+ /*@internal*/
Project.prototype.getSourceFileLike = function (fileName) {
return this.projectService.getSourceFileLike(fileName, this);
};
@@ -122208,13 +124797,18 @@
}
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];
@@ -122230,7 +124824,7 @@
}
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) {
@@ -122242,13 +124836,14 @@
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) });
@@ -122275,6 +124870,7 @@
}
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);
@@ -122282,6 +124878,9 @@
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);
@@ -122292,7 +124891,9 @@
}
});
}
+ // Release external files
ts.forEach(this.externalFiles, function (externalFile) { return _this.detachScriptInfoIfNotRoot(externalFile); });
+ // Always remove root files from the project
for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) {
var root = _c[_b];
root.detachFromProject(this);
@@ -122307,15 +124908,19 @@
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);
}
@@ -122326,12 +124931,14 @@
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;
};
@@ -122341,6 +124948,7 @@
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) {
@@ -122357,6 +124965,7 @@
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);
@@ -122425,6 +125034,7 @@
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);
@@ -122432,6 +125042,7 @@
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);
@@ -122442,6 +125053,7 @@
this.removeRoot(info);
}
if (fileExists) {
+ // If file is present, just remove the resolutions for the file
this.resolutionCache.removeResolutionsOfFile(info.path);
}
else {
@@ -122462,9 +125074,14 @@
this.dirty = true;
}
};
+ /* @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 () {
this.resolutionCache.startRecordingFilesWithChangedResolutions();
var hasNewProgram = this.updateGraphWorker();
@@ -122473,9 +125090,18 @@
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) {
this.lastCachedUnresolvedImportsList = getUnresolvedImports(this.program, this.cachedUnresolvedImportsPerFile);
}
@@ -122489,12 +125115,16 @@
}
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;
};
@@ -122510,11 +125140,14 @@
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) {
@@ -122522,6 +125155,8 @@
var f = _a[_i];
var newFile = this.program.getSourceFileByPath(f.resolvedPath);
if (!newFile || (f.resolvedPath === f.path && newFile.resolvedPath !== f.path)) {
+ // new program does not contain this file - detach it from the project
+ // - remove resolutions only if the new program doesnt contain source file by the path (not resolvedPath since path is used for resolution)
this.detachScriptInfoFromProject(f.fileName, !!this.program.getSourceFileByPath(f.path));
}
}
@@ -122531,14 +125166,22 @@
}
});
}
- 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); });
@@ -122564,9 +125207,10 @@
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", this);
+ }, ts.PollingInterval.Medium, "Missing file" /* MissingFile */, this);
return fileWatcher;
};
Project.prototype.isWatchedMissingFile = function (path) {
@@ -122596,6 +125240,7 @@
}
return strBuilder;
};
+ /*@internal*/
Project.prototype.print = function (counter) {
this.writeLog("Project '" + this.projectName + "' (" + ProjectKind[this.projectKind] + ") " + (counter === undefined ? "" : counter));
this.writeLog(this.filesToString(this.projectService.logger.hasLevel(server.LogLevel.verbose)));
@@ -122608,6 +125253,7 @@
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();
@@ -122615,7 +125261,9 @@
this.markAsDirty();
}
};
+ /* @internal */
Project.prototype.getChangesSinceVersion = function (lastKnownVersion) {
+ // Update the graph only if initial configured project load is not pending
if (!this.isInitialLoadPending()) {
server.updateProjectIfDirty(this);
}
@@ -122629,10 +125277,13 @@
};
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));
@@ -122654,6 +125305,7 @@
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);
@@ -122662,6 +125314,7 @@
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);
@@ -122672,17 +125325,23 @@
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) {
+ // 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";
+ // Provide global: true so plugins can detect why they can't find their config
this_1.projectService.logger.info("Loading global plugin " + globalPluginName);
this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides);
};
var this_1 = 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);
@@ -122701,6 +125360,7 @@
if (resolvedModule) {
var configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name);
if (configurationOverride) {
+ // Preserve the name property since it's immutable
var pluginName = pluginConfigEntry.name;
pluginConfigEntry = configurationOverride;
pluginConfigEntry.name = pluginName;
@@ -122741,6 +125401,7 @@
this.projectService.logger.info("Plugin activation failed: " + e);
}
};
+ /*@internal*/
Project.prototype.onPluginConfigurationChanged = function (pluginName, configuration) {
this.plugins.filter(function (plugin) { return plugin.name === pluginName; }).forEach(function (plugin) {
if (plugin.module.onConfigurationChanged) {
@@ -122748,6 +125409,7 @@
}
});
};
+ /** 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();
};
@@ -122766,6 +125428,7 @@
return server.emptyArray;
var unresolvedImports;
file.resolvedModules.forEach(function (resolvedModule, name) {
+ // pick unresolved non-relative names
if ((!resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) &&
!ts.isExternalModuleNameRelative(name) &&
!ambientModules.some(function (m) { return m === name; })) {
@@ -122775,10 +125438,19 @@
return unresolvedImports || server.emptyArray;
});
}
- 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, pluginConfigOverrides) {
- 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) {
@@ -122794,6 +125466,7 @@
}
};
InferredProject.prototype.setCompilerOptions = function (options) {
+ // Avoid manipulating the given options directly
if (!options && !this.getCompilationSettings()) {
return;
}
@@ -122811,7 +125484,7 @@
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);
};
@@ -122820,14 +125493,18 @@
_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;
};
@@ -122854,17 +125531,34 @@
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, cachedDirectoryStructureHost) {
- var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, false, undefined, {}, false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this;
+ var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry,
+ /*hasExplicitListOfFiles*/ false,
+ /*lastFileExceededProgramSize*/ undefined,
+ /*compilerOptions*/ {},
+ /*compileOnSaveEnabled*/ false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this;
+ /*@internal*/
_this.canConfigFileJsonReportNoInputFiles = false;
+ /** Ref count to the project when opened from external project */
_this.externalProjectRefCount = 0;
_this.isInitialLoadPending = ts.returnTrue;
+ /*@internal*/
_this.sendLoadingProjectFinish = false;
_this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName));
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 () {
this.isInitialLoadPending = ts.returnFalse;
var reloadLevel = this.pendingReload;
@@ -122885,9 +125579,9 @@
}
this.projectService.sendProjectLoadingFinishEvent(this);
this.projectService.sendProjectTelemetry(this);
- this.projectService.sendSurveyReady(this);
return result;
};
+ /*@internal*/
ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () {
return this.directoryStructureHost;
};
@@ -122900,22 +125594,27 @@
ConfiguredProject.prototype.updateReferences = function (refs) {
this.projectReferences = refs;
};
+ /*@internal*/
ConfiguredProject.prototype.forEachResolvedProjectReference = function (cb) {
var program = this.getCurrentProgram();
return program && program.forEachResolvedProjectReference(cb);
};
+ /*@internal*/
ConfiguredProject.prototype.enablePluginsWithOptions = function (options, pluginConfigOverrides) {
var host = this.projectService.host;
if (!host.require) {
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];
@@ -122924,9 +125623,15 @@
}
this.enableGlobalPlugins(options, pluginConfigOverrides);
};
+ /**
+ * 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;
};
@@ -122939,10 +125644,14 @@
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);
@@ -122959,51 +125668,70 @@
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;
};
+ /*@internal*/
ConfiguredProject.prototype.hasExternalProjectRef = function () {
return !!this.externalProjectRefCount;
};
ConfiguredProject.prototype.getEffectiveTypeRoots = function () {
return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || [];
};
+ /*@internal*/
ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (fileNameResult) {
ts.updateErrorForNoInputFiles(fileNameResult, this.getConfigFilePath(), this.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles);
};
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);
- 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;
+ /*@internal*/
+ function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, pluginConfigOverrides) {
+ 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 = [];
+ _this.enableGlobalPlugins(_this.getCompilerOptions(), pluginConfigOverrides);
return _this;
}
ExternalProject.prototype.updateGraph = function () {
var result = _super.prototype.updateGraph.call(this);
this.projectService.sendProjectTelemetry(this);
- this.projectService.sendSurveyReady(this);
return result;
};
ExternalProject.prototype.getExcludedFiles = function () {
@@ -123029,11 +125757,12 @@
var server;
(function (server) {
server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;
+ /*@internal*/
server.maxFileSize = 4 * 1024 * 1024;
+ // tslint:disable variable-name
server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground";
server.ProjectLoadingStartEvent = "projectLoadingStart";
server.ProjectLoadingFinishEvent = "projectLoadingFinish";
- server.SurveyReady = "surveyReady";
server.LargeFileReferencedEvent = "largeFileReferenced";
server.ConfigFileDiagEvent = "configFileDiag";
server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
@@ -123045,6 +125774,7 @@
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");
});
@@ -123059,25 +125789,47 @@
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,
@@ -123109,18 +125861,19 @@
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;
+ /*@internal*/
function convertUserPreferences(preferences) {
var lazyConfiguredProjectsFromExternalProject = preferences.lazyConfiguredProjectsFromExternalProject, userPreferences = __rest(preferences, ["lazyConfiguredProjectsFromExternalProject"]);
return userPreferences;
@@ -123142,7 +125895,7 @@
});
}
}
- 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); }); },
};
@@ -123178,6 +125931,7 @@
function isScriptInfoWatchedFromNodeModules(info) {
return !info.isScriptOpen() && info.mTime !== undefined;
}
+ /*@internal*/
function updateProjectIfDirty(project) {
return project.dirty && project.updateGraph();
}
@@ -123187,28 +125941,67 @@
project.projectOptions = true;
}
}
- var ProjectService = (function () {
+ var ProjectService = /** @class */ (function () {
function ProjectService(opts) {
var _this = this;
+ /**
+ * Container of all known scripts
+ */
+ /*@internal*/
this.filenameToScriptInfo = ts.createMap();
this.scriptInfoInNodeModulesWatchers = 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 = ts.createMap();
this.pendingProjectUpdates = ts.createMap();
+ /* @internal */
this.pendingEnsureProjectForOpenFiles = false;
+ /** Tracks projects that we have already sent telemetry for. */
this.seenProjects = ts.createMap();
- this.seenSurveyProjects = ts.createMap();
this.host = opts.host;
this.logger = opts.logger;
this.cancellationToken = opts.cancellationToken;
@@ -123256,26 +126049,33 @@
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;
@@ -123288,16 +126088,18 @@
};
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)) {
@@ -123318,10 +126120,12 @@
}
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);
@@ -123329,13 +126133,15 @@
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();
}
}
@@ -123346,15 +126152,17 @@
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)) {
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) {
@@ -123368,12 +126176,7 @@
};
this.eventHandler(event);
};
- ProjectService.prototype.sendSurveyReadyEvent = function (surveyId) {
- if (!this.eventHandler) {
- return;
- }
- this.eventHandler({ eventName: server.SurveyReady, data: { surveyId: surveyId } });
- };
+ /* @internal */
ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) {
if (!this.eventHandler) {
return;
@@ -123384,6 +126187,7 @@
};
this.eventHandler(event);
};
+ /* @internal */
ProjectService.prototype.sendProjectLoadingStartEvent = function (project, reason) {
if (!this.eventHandler) {
return;
@@ -123395,6 +126199,7 @@
};
this.eventHandler(event);
};
+ /* @internal */
ProjectService.prototype.sendProjectLoadingFinishEvent = function (project) {
if (!this.eventHandler || !project.sendLoadingProjectFinish) {
return;
@@ -123406,6 +126211,7 @@
};
this.eventHandler(event);
};
+ /* @internal */
ProjectService.prototype.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles = function (project) {
this.delayUpdateProjectGraph(project);
this.delayEnsureProjectForOpenFiles();
@@ -123422,6 +126228,8 @@
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) {
@@ -123432,6 +126240,14 @@
}
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)) {
@@ -123452,11 +126268,13 @@
}
return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName));
};
+ /* @internal */
ProjectService.prototype.forEachProject = function (cb) {
this.externalProjects.forEach(cb);
this.configuredProjects.forEach(cb);
this.inferredProjects.forEach(cb);
};
+ /* @internal */
ProjectService.prototype.forEachEnabledProject = function (cb) {
this.forEachProject(function (project) {
if (!project.isOrphan() && project.languageServiceEnabled) {
@@ -123467,10 +126285,12 @@
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);
return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : undefined;
};
+ /* @internal */
ProjectService.prototype.ensureDefaultProjectForFile = function (fileName) {
return this.tryGetDefaultProjectForFile(fileName) || this.doEnsureDefaultProjectForFile(fileName);
};
@@ -123483,6 +126303,13 @@
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();
@@ -123502,7 +126329,7 @@
};
ProjectService.prototype.getPreferences = function (file) {
var info = this.getScriptInfoForNormalizedPath(file);
- return info && info.getPreferences() || this.hostConfiguration.preferences;
+ return __assign({}, this.hostConfiguration.preferences, info && info.getPreferences());
};
ProjectService.prototype.getHostFormatCodeOptions = function () {
return this.hostConfiguration.formatCodeOptions;
@@ -123520,9 +126347,12 @@
info.containingProjects.forEach(function (project) { return project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(info.path); });
}
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);
this.handleSourceMapProjects(info);
@@ -123530,6 +126360,7 @@
}
};
ProjectService.prototype.handleSourceMapProjects = function (info) {
+ // Change in d.ts, update source projects as well
if (info.sourceMapFilePath) {
if (ts.isString(info.sourceMapFilePath)) {
var sourceMapFileInfo = this.getScriptInfoForPath(info.sourceMapFilePath);
@@ -123539,6 +126370,7 @@
this.delayUpdateSourceInfoProjects(info.sourceMapFilePath.sourceInfos);
}
}
+ // Change in mapInfo, update declarationProjects and source projects
this.delayUpdateSourceInfoProjects(info.sourceInfos);
if (info.declarationInfoPath) {
this.delayUpdateProjectsOfScriptInfoPath(info.declarationInfoPath);
@@ -123560,11 +126392,14 @@
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.handleSourceMapProjects(info);
info.closeSourceMapFileWatcher();
+ // need to recalculate source map from declaration file
if (info.declarationInfoPath) {
var declarationInfo = this.getScriptInfoForPath(info.declarationInfoPath);
if (declarationInfo) {
@@ -123573,58 +126408,85 @@
}
}
};
+ /**
+ * 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);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
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" /* WildcardDirectory */, 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;
project.pendingReloadReason = "Change in config file detected";
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) {
var _this = this;
this.logger.info("`remove Project::");
project.print();
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), "Found script Info still attached to project", function () { return project.projectName + ": ScriptInfos still attached: " + JSON.stringify(ts.mapDefined(ts.arrayFrom(_this.filenameToScriptInfo.values()), function (info) { return info.isAttached(project) ? info : undefined; })); }); });
}
+ // Remove the project from pending project updates
this.pendingProjectUpdates.delete(project.getProjectName());
switch (project.projectKind) {
case server.ProjectKind.External:
@@ -123641,6 +126503,7 @@
break;
}
};
+ /*@internal*/
ProjectService.prototype.assignOrphanScriptInfoToInferredProject = function (info, projectRootPath) {
ts.Debug.assert(info.isOrphan());
var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) ||
@@ -123648,6 +126511,7 @@
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);
}
@@ -123657,12 +126521,21 @@
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);
@@ -123670,8 +126543,25 @@
}
return project;
};
- ProjectService.prototype.closeOpenFile = function (info) {
+ ProjectService.prototype.assignOrphanScriptInfosToInferredProject = function () {
var _this = this;
+ // 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);
+ }
+ });
+ };
+ /**
+ * 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, skipAssignOrphanScriptInfosToInferredProject) {
+ // 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);
@@ -123679,6 +126569,7 @@
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];
@@ -123686,50 +126577,69 @@
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) {
- this.openFiles.forEach(function (projectRootPath, path) {
- var info = _this.getScriptInfoForPath(path);
- if (info.isOrphan()) {
- _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
- }
- });
+ if (!skipAssignOrphanScriptInfosToInferredProject && ensureProjectsForOpenFiles) {
+ this.assignOrphanScriptInfosToInferredProject();
}
+ // 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);
}
else {
this.handleDeletedFile(info);
}
+ return ensureProjectsForOpenFiles;
};
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) {
+ // 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;
}
+ // 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)) {
@@ -123737,27 +126647,34 @@
}
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) {
+ // The existance might not be set if the file watcher is not invoked by the time config project is created by external project
configFileExistenceInfo.exists = true;
+ // 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; });
};
@@ -123766,12 +126683,16 @@
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);
}
};
@@ -123788,25 +126709,36 @@
});
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");
+ watches.push("Config file" /* ConfigFile */);
}
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());
@@ -123814,11 +126746,18 @@
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);
@@ -123827,38 +126766,59 @@
}
});
};
+ /**
+ * 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) {
@@ -123868,6 +126828,7 @@
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);
@@ -123889,6 +126850,16 @@
} 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;
if (isOpenScriptInfo(info))
@@ -123926,6 +126897,7 @@
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);
};
@@ -123935,6 +126907,7 @@
ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) {
return findProjectByName(projectFileName, this.externalProjects);
};
+ /** 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;
@@ -123952,6 +126925,7 @@
totalNonTsFileSize += this.host.getFileSize(fileName);
if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) {
this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize));
+ // Keep the size as zero since it's disabled
return fileName;
}
}
@@ -123965,30 +126939,22 @@
var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host;
return fileNames.map(function (f) { return propertyReader.getFileName(f); })
.filter(function (name) { return hasTSFileExtension(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,
+ /*projectFilePath*/ undefined, this.currentPluginConfigOverrides);
project.excludedFiles = excludedFiles;
this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition);
this.externalProjects.push(project);
return project;
};
- ProjectService.prototype.sendSurveyReady = function (project) {
- if (this.seenSurveyProjects.has(project.projectName)) {
- return;
- }
- if (project.getCompilerOptions().checkJs !== undefined) {
- var name = "checkJs";
- this.logger.info("Survey " + name + " is ready");
- this.sendSurveyReadyEvent(name);
- this.seenSurveyProjects.set(project.projectName, true);
- }
- };
+ /*@internal*/
ProjectService.prototype.sendProjectTelemetry = function (project) {
if (this.seenProjects.has(project.projectName)) {
setProjectOptionsUsed(project);
@@ -124003,7 +126969,7 @@
setProjectOptionsUsed(project);
var data = {
projectId: this.host.createSHA256Hash(project.projectName),
- fileStats: server.countEachFileTypes(project.getScriptInfos(), true),
+ fileStats: server.countEachFileTypes(project.getScriptInfos(), /*includeSizes*/ true),
compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()),
typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()),
extends: projectOptions && projectOptions.configHasExtendsProperty,
@@ -124038,45 +127004,57 @@
};
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
this.logger.info("Opened configuration file " + configFileName);
var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost);
- project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file", 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" /* ConfigFile */, project);
this.configuredProjects.set(project.canonicalConfigFilePath, project);
this.setConfigFileExistenceByNewConfiguredProject(project);
return project;
};
+ /* @internal */
ProjectService.prototype.createConfiguredProjectWithDelayLoad = function (configFileName, reason) {
var project = this.createConfiguredProject(configFileName);
project.pendingReload = ts.ConfigFileProgramReloadLevel.Full;
project.pendingReloadReason = reason;
return project;
};
+ /* @internal */
ProjectService.prototype.createAndLoadConfiguredProject = function (configFileName, reason) {
var project = this.createConfiguredProject(configFileName);
this.loadConfiguredProject(project, reason);
return project;
};
+ /* @internal */
ProjectService.prototype.createLoadAndUpdateConfiguredProject = function (configFileName, reason) {
var project = this.createAndLoadConfiguredProject(configFileName, reason);
project.updateGraph();
return project;
};
+ /**
+ * Read the config file of the project, and update the project root file names.
+ */
+ /* @internal */
ProjectService.prototype.loadConfiguredProject = function (project, reason) {
this.sendProjectLoadingStartEvent(project, reason);
+ // Read updated contents from disk
var configFilename = ts.normalizePath(project.getConfigFilePath());
- 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 configFileErrors = result.parseDiagnostics;
- var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions);
+ var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename),
+ /*existingOptions*/ {}, configFilename,
+ /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions);
if (parsedCommandLine.errors.length) {
configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors);
}
ts.Debug.assert(!!parsedCommandLine.fileNames);
var compilerOptions = parsedCommandLine.options;
+ // Update the project
if (!project.projectOptions) {
project.projectOptions = {
configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined,
@@ -124096,11 +127074,11 @@
}
else {
project.enableLanguageService();
- project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories));
+ project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories)); // TODO: GH#18217
}
project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides);
var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles());
- this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave);
+ this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave); // TODO: GH#18217
};
ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) {
var projectRootFilesMap = project.getRootFilesMap();
@@ -124112,11 +127090,12 @@
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;
@@ -124124,22 +127103,27 @@
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);
@@ -124147,28 +127131,43 @@
}
});
}
+ // 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.updateRootAndOptionsOfNonInferredProject = 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.addFilesToNonInferredProject(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);
this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader);
return project.updateGraph();
};
+ /**
+ * Read the config file of the project again by clearing the cache and update the project graph
+ */
+ /* @internal */
ProjectService.prototype.reloadConfiguredProject = function (project, reason) {
+ // 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);
+ // Load project from the disk
this.loadConfiguredProject(project, reason);
project.updateGraph();
this.sendConfigFileDiagEvent(project, configFileName);
@@ -124190,21 +127189,28 @@
}
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;
@@ -124215,14 +127221,24 @@
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 &&
@@ -124234,7 +127250,7 @@
return this.createInferredProject(currentDirectory);
};
ProjectService.prototype.createInferredProject = function (currentDirectory, isSingleInferredProject, projectRootPath) {
- var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects;
+ var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; // TODO: GH#18217
var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory, this.currentPluginConfigOverrides);
if (isSingleInferredProject) {
this.inferredProjects.unshift(project);
@@ -124244,12 +127260,15 @@
}
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);
@@ -124258,6 +127277,7 @@
var configProject = this.configuredProjects.get(this.toPath(uncheckedFileName));
return configProject && configProject.getCompilerOptions().configFile;
};
+ /* @internal */
ProjectService.prototype.logErrorForScriptInfoNotFound = function (fileName) {
var names = ts.arrayFrom(this.filenameToScriptInfo.entries()).map(function (_a) {
var path = _a[0], scriptInfo = _a[1];
@@ -124265,6 +127285,11 @@
});
this.logger.msg("Could not find file " + JSON.stringify(fileName) + ".\nAll files are: " + JSON.stringify(names), server.Msg.Err);
};
+ /**
+ * 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) {
@@ -124278,6 +127303,7 @@
function combineProjects(toAddInfo) {
if (toAddInfo !== info) {
var _loop_3 = 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 &&
@@ -124301,12 +127327,14 @@
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 indexOfNodeModules = info.path.indexOf("/node_modules/");
if (!this.host.getModifiedTime || indexOfNodeModules === -1) {
- info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.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, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info" /* ClosedScriptInfo */);
}
else {
info.mTime = this.getModifiedTime(info);
@@ -124316,6 +127344,7 @@
};
ProjectService.prototype.watchClosedScriptInfoInNodeModules = function (dir) {
var _this = this;
+ // Watch only directory
var existing = this.scriptInfoInNodeModulesWatchers.get(dir);
if (existing) {
existing.refCount++;
@@ -124324,8 +127353,9 @@
var watchDir = dir + "/node_modules";
var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) {
var fileOrDirectoryPath = _this.toPath(fileOrDirectory);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
+ // Has extension
ts.Debug.assert(result.refCount > 0);
if (watchDir === fileOrDirectoryPath) {
_this.refreshScriptInfosInDirectory(watchDir);
@@ -124337,11 +127367,12 @@
_this.refreshScriptInfo(info);
}
}
+ // Folder
else if (!ts.hasExtension(fileOrDirectoryPath)) {
_this.refreshScriptInfosInDirectory(fileOrDirectoryPath);
}
}
- }, 1, "node_modules for closed script infos in them");
+ }, 1 /* Recursive */, "node_modules for closed script infos in them" /* NodeModulesForClosedScriptInfo */);
var result = {
close: function () {
if (result.refCount === 1) {
@@ -124385,16 +127416,20 @@
};
ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath = function (fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn) {
if (ts.isRootedDiskPath(fileName) || server.isDynamicFileName(fileName)) {
- return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, false, undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn);
+ return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn);
}
+ // This is non rooted path with different current directory than project service current directory
+ // Only paths recognized are open relative file paths
var info = this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName));
if (info) {
return info;
}
+ // This means triple slash references wont be resolved in dynamic and unsaved files
+ // which is intentional since we dont know what it means to be relative to non disk files
return undefined;
};
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);
@@ -124409,20 +127444,24 @@
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 or in context of host currentDirectory"; });
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, this.filenameToScriptInfoVersion.get(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) && !isDynamic) {
+ // 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) {
@@ -124434,6 +127473,9 @@
}
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));
@@ -124441,13 +127483,17 @@
ProjectService.prototype.getScriptInfoForPath = function (fileName) {
return this.filenameToScriptInfo.get(fileName);
};
+ /*@internal*/
ProjectService.prototype.getDocumentPositionMapper = function (project, generatedFileName, sourceFileName) {
var _this = this;
+ // Since declaration info and map file watches arent updating project's directory structure host (which can cache file structure) use host
var declarationInfo = this.getOrCreateScriptInfoNotOpenedByClient(generatedFileName, project.currentDirectory, this.host);
if (!declarationInfo)
return undefined;
- declarationInfo.getSnapshot();
+ // Try to get from cache
+ declarationInfo.getSnapshot(); // Ensure synchronized
if (ts.isString(declarationInfo.sourceMapFilePath)) {
+ // Ensure mapper is synchronized
var sourceMapFileInfo_1 = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath);
if (sourceMapFileInfo_1) {
sourceMapFileInfo_1.getSnapshot();
@@ -124463,8 +127509,10 @@
return undefined;
}
else if (declarationInfo.sourceMapFilePath !== undefined) {
+ // Doesnt have sourceMap
return undefined;
}
+ // Create the mapper
var sourceMapFileInfo;
var mapFileNameFromDeclarationInfo;
var readMapFile = function (mapFileName, mapFileNameFromDts) {
@@ -124481,7 +127529,7 @@
};
var projectName = project.projectName;
var documentPositionMapper = ts.getDocumentPositionMapper({ getCanonicalFileName: this.toCanonicalFileName, log: function (s) { return _this.logger.info(s); }, getSourceFileLike: function (f) { return _this.getSourceFileLike(f, projectName, declarationInfo); } }, declarationInfo.fileName, declarationInfo.getLineInfo(), readMapFile);
- readMapFile = undefined;
+ readMapFile = undefined; // Remove ref to project
if (sourceMapFileInfo) {
declarationInfo.sourceMapFilePath = sourceMapFileInfo.path;
sourceMapFileInfo.declarationInfoPath = declarationInfo.path;
@@ -124503,6 +127551,7 @@
};
ProjectService.prototype.addSourceInfoToSourceMap = function (sourceFileName, project, sourceInfos) {
if (sourceFileName) {
+ // Attach as source
var sourceInfo = this.getOrCreateScriptInfoNotOpenedByClient(sourceFileName, project.currentDirectory, project.directoryStructureHost);
(sourceInfos || (sourceInfos = ts.createMap())).set(sourceInfo.path, true);
}
@@ -124513,13 +127562,15 @@
var fileWatcher = this.watchFactory.watchFile(this.host, mapFileName, function () {
var declarationInfo = _this.getScriptInfoForPath(declarationInfoPath);
if (declarationInfo && declarationInfo.sourceMapFilePath && !ts.isString(declarationInfo.sourceMapFilePath)) {
+ // Update declaration and source projects
_this.delayUpdateProjectGraphs(declarationInfo.containingProjects);
_this.delayUpdateSourceInfoProjects(declarationInfo.sourceMapFilePath.sourceInfos);
declarationInfo.closeSourceMapFileWatcher();
}
- }, ts.PollingInterval.High, "Missing source map file");
+ }, ts.PollingInterval.High, "Missing source map file" /* MissingSourceMapFile */);
return fileWatcher;
};
+ /*@internal*/
ProjectService.prototype.getSourceFileLike = function (fileName, projectNameOrProject, declarationInfo) {
var project = projectNameOrProject.projectName ? projectNameOrProject : this.findProject(projectNameOrProject);
if (project) {
@@ -124528,17 +127579,21 @@
if (sourceFile && sourceFile.resolvedPath === path)
return sourceFile;
}
+ // Need to look for other files.
var info = this.getOrCreateScriptInfoNotOpenedByClient(fileName, (project || this).currentDirectory, project ? project.directoryStructureHost : this.host);
if (!info)
return undefined;
+ // Attach as source
if (declarationInfo && ts.isString(declarationInfo.sourceMapFilePath) && info !== declarationInfo) {
var sourceMapInfo = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath);
if (sourceMapInfo) {
(sourceMapInfo.sourceInfos || (sourceMapInfo.sourceInfos = ts.createMap())).set(info.path, true);
}
}
+ // Key doesnt matter since its only for text and lines
if (info.cacheSourceFile)
return info.cacheSourceFile.sourceFile;
+ // Create sourceFileLike
if (!info.sourceFileLike) {
info.sourceFileLike = {
get text() {
@@ -124576,6 +127631,7 @@
var lazyConfiguredProjectsFromExternalProject = this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject;
this.hostConfiguration.preferences = __assign({}, this.hostConfiguration.preferences, args.preferences);
if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) {
+ // Load configured projects for external projects that are pending reload
this.configuredProjects.forEach(function (project) {
if (project.hasExternalProjectRef() &&
project.pendingReload === ts.ConfigFileProgramReloadLevel.Full &&
@@ -124587,6 +127643,8 @@
}
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");
}
@@ -124595,26 +127653,51 @@
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, "User requested reload projects");
+ // 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, "User requested reload projects");
this.ensureProjectForOpenFiles();
};
ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) {
- this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, true, ignoreIfNotRootOfInferredProject ?
- function (isRootOfInferredProject) { return isRootOfInferredProject; } :
- ts.returnTrue, "Change in config file detected");
+ // 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
+ "Change in config file detected");
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, reason) {
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) || _this.createConfiguredProject(configFileName);
@@ -124625,6 +127708,7 @@
_this.delayUpdateProjectGraph(project);
}
else {
+ // reload from the disk
_this.reloadConfiguredProject(project, reason);
}
updatedProjects.set(configFileName, true);
@@ -124632,26 +127716,51 @@
}
});
};
+ /**
+ * 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);
}
});
@@ -124660,9 +127769,15 @@
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().tryGetSourcePosition(location);
if (!originalLocation)
@@ -124677,10 +127792,12 @@
var configuredProject = this.findConfiguredProjectByProjectName(configFileName) ||
this.createAndLoadConfiguredProject(configFileName, "Creating project for original file: " + originalFileInfo.fileName + " for location: " + location.fileName);
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);
@@ -124694,68 +127811,104 @@
project.originalConfiguredProjects.set(originalProject.canonicalConfigFilePath, true);
}
};
+ /** @internal */
ProjectService.prototype.fileExists = function (fileName) {
return !!this.getScriptInfoForNormalizedPath(fileName) || this.host.fileExists(fileName);
};
ProjectService.prototype.findExternalProjectContainingOpenScriptInfo = function (info) {
return ts.find(this.externalProjects, function (proj) {
+ // Ensure project structure is up-to-date to check if info is present in external project
updateProjectIfDirty(proj);
return proj.containsScriptInfo(info);
});
};
- ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
+ ProjectService.prototype.getOrCreateOpenScriptInfo = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
+ var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); // TODO: GH#18217
+ this.openFiles.set(info.path, projectRootPath);
+ return info;
+ };
+ ProjectService.prototype.assignProjectToOpenedScriptInfo = function (info) {
var configFileName;
var configFileErrors;
- var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent);
- 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.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + fileName + " to open");
+ project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + info.fileName + " to open");
+ // 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 {
configFileErrors = project.getAllProjectErrors();
- this.sendConfigFileDiagEvent(project, fileName);
+ this.sendConfigFileDiagEvent(project, info.fileName);
}
}
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(this.openFiles.has(info.path));
+ this.assignOrphanScriptInfoToInferredProject(info, this.openFiles.get(info.path));
}
ts.Debug.assert(!info.isOrphan());
+ return { configFileName: configFileName, configFileErrors: configFileErrors };
+ };
+ ProjectService.prototype.cleanupAfterOpeningFile = function () {
+ // 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.removeOrphanScriptInfos();
this.printProjects();
+ };
+ ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
+ var info = this.getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath);
+ var result = this.assignProjectToOpenedScriptInfo(info);
+ this.cleanupAfterOpeningFile();
this.telemetryOnOpenFile(info);
- return { configFileName: configFileName, configFileErrors: configFileErrors };
+ return result;
};
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
project.forEachResolvedProjectReference(function (ref) {
if (ref) {
var refProject = _this.configuredProjects.get(ref.sourceFile.path);
@@ -124766,6 +127919,7 @@
});
}
});
+ // Remove all the non marked projects
toRemoveConfiguredProjects.forEach(function (project) { return _this.removeProject(project); });
function markOriginalProjectsAsUsed(project) {
if (!project.isOrphan() && project.originalConfiguredProjects) {
@@ -124777,7 +127931,9 @@
var _this = this;
var toRemoveScriptInfos = ts.cloneMap(this.filenameToScriptInfo);
this.filenameToScriptInfo.forEach(function (info) {
+ // If script info is open or orphan, retain it and its dependencies
if (!info.isScriptOpen() && info.isOrphan()) {
+ // Otherwise if there is any source info that is alive, this alive too
if (!info.sourceMapFilePath)
return;
var sourceInfos = void 0;
@@ -124797,10 +127953,12 @@
return;
}
}
+ // Retain this script info
toRemoveScriptInfos.delete(info.path);
if (info.sourceMapFilePath) {
var sourceInfos = void 0;
if (ts.isString(info.sourceMapFilePath)) {
+ // And map file info and source infos
toRemoveScriptInfos.delete(info.sourceMapFilePath);
var sourceMapInfo = _this.getScriptInfoForPath(info.sourceMapFilePath);
sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos;
@@ -124814,6 +127972,7 @@
}
});
toRemoveScriptInfos.forEach(function (info) {
+ // if there are not projects that include this script info - delete it
_this.stopWatchingScriptInfo(info);
_this.deleteScriptInfo(info);
info.closeSourceMapFileWatcher();
@@ -124830,12 +127989,13 @@
var info = { checkJs: !!project.getSourceFile(scriptInfo.path).checkJsDirective };
this.eventHandler({ eventName: server.OpenFileInfoTelemetryEvent, data: { info: info } });
};
- ProjectService.prototype.closeClientFile = function (uncheckedFileName) {
+ ProjectService.prototype.closeClientFile = function (uncheckedFileName, skipAssignOrphanScriptInfosToInferredProject) {
var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName));
- if (info) {
- this.closeOpenFile(info);
- }
+ var result = info ? this.closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) : false;
+ if (!skipAssignOrphanScriptInfosToInferredProject) {
this.printProjects();
+ }
+ return result;
};
ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) {
var _loop_4 = function (proj) {
@@ -124847,6 +128007,7 @@
_loop_4(proj);
}
};
+ /* @internal */
ProjectService.prototype.synchronizeProjectList = function (knownProjects) {
var files = [];
this.collectChanges(knownProjects, this.externalProjects, files);
@@ -124854,34 +128015,61 @@
this.collectChanges(knownProjects, this.inferredProjects, files);
return files;
};
+ /* @internal */
ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) {
+ var _this = this;
+ var openScriptInfos;
+ var assignOrphanScriptInfosToInferredProject = false;
if (openFiles) {
- for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) {
- var file = openFiles_1[_i];
+ while (true) {
+ var _a = openFiles.next(), file = _a.value, done = _a.done;
+ if (done)
+ break;
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);
+ // Create script infos so we have the new content for all the open files before we do any updates to projects
+ var info = this.getOrCreateOpenScriptInfo(scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName), file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent, file.projectRootPath ? server.toNormalizedPath(file.projectRootPath) : undefined);
+ (openScriptInfos || (openScriptInfos = [])).push(info);
}
}
if (changedFiles) {
- for (var _a = 0, changedFiles_2 = changedFiles; _a < changedFiles_2.length; _a++) {
- var file = changedFiles_2[_a];
+ while (true) {
+ var _b = changedFiles.next(), file = _b.value, done = _b.done;
+ if (done)
+ break;
var scriptInfo = this.getScriptInfo(file.fileName);
ts.Debug.assert(!!scriptInfo);
+ // Make edits to script infos and marks containing project as dirty
this.applyChangesToFile(scriptInfo, file.changes);
}
}
if (closedFiles) {
- for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) {
- var file = closedFiles_1[_b];
- this.closeClientFile(file);
- }
- }
+ for (var _i = 0, closedFiles_1 = closedFiles; _i < closedFiles_1.length; _i++) {
+ var file = closedFiles_1[_i];
+ // Close files, but dont assign projects to orphan open script infos, that part comes later
+ assignOrphanScriptInfosToInferredProject = this.closeClientFile(file, /*skipAssignOrphanScriptInfosToInferredProject*/ true) || assignOrphanScriptInfosToInferredProject;
+ }
+ }
+ // All the script infos now exist, so ok to go update projects for open files
+ if (openScriptInfos) {
+ openScriptInfos.forEach(function (info) { return _this.assignProjectToOpenedScriptInfo(info); });
+ }
+ // While closing files there could be open files that needed assigning new inferred projects, do it now
+ if (assignOrphanScriptInfosToInferredProject) {
+ this.assignOrphanScriptInfosToInferredProject();
+ }
+ // Cleanup projects
+ this.cleanupAfterOpeningFile();
+ // Telemetry
+ ts.forEach(openScriptInfos, function (info) { return _this.telemetryOnOpenFile(info); });
+ this.printProjects();
};
+ /* @internal */
ProjectService.prototype.applyChangesToFile = function (scriptInfo, changes) {
- for (var i = changes.length - 1; i >= 0; i--) {
- var change = changes[i];
+ while (true) {
+ var _a = changes.next(), change = _a.value, done = _a.done;
+ if (done)
+ break;
scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText);
}
};
@@ -124906,6 +128094,7 @@
this.externalProjectToConfiguredProjectMap.delete(fileName);
}
else {
+ // close external project
var externalProject = this.findExternalProjectByProjectName(uncheckedFileName);
if (externalProject) {
this.removeProject(externalProject);
@@ -124914,6 +128103,7 @@
};
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);
@@ -124921,8 +128111,10 @@
for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) {
var externalProject = projects_3[_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);
});
@@ -124938,6 +128130,7 @@
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 [];
}
@@ -124951,9 +128144,12 @@
var root = normalizedNames_1[_i];
if (rule.match.test(root)) {
this_2.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);
}
@@ -124967,9 +128163,13 @@
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]);
@@ -124987,6 +128187,7 @@
}
}
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);
@@ -125017,7 +128218,10 @@
if (typeName !== undefined) {
this_3.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist");
excludedFiles.push(normalizedNames[i]);
+ // *exclude* it from the project...
exclude = true;
+ // ... but *include* it in the list of types to acquire
+ // Same best-effort dedupe as above
if (typeAcqInclude.indexOf(typeName) < 0) {
typeAcqInclude.push(typeName);
}
@@ -125025,6 +128229,7 @@
}
}
if (!exclude) {
+ // Exclude any minified files that get this far
if (/^.+[\.-]min\.js$/.test(normalizedNames[i])) {
excludedFiles.push(normalizedNames[i]);
}
@@ -125042,6 +128247,8 @@
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;
@@ -125067,6 +128274,7 @@
rootFiles.push(file);
}
}
+ // sort config files to simplify comparison later
if (tsConfigFiles) {
tsConfigFiles.sort();
}
@@ -125083,17 +128291,24 @@
else {
externalProject.enableLanguageService();
}
+ // external project already exists and not config files were added - update the project and return;
+ // The graph update here isnt postponed since any file open operation needs all updated external projects
this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave);
externalProject.updateGraph();
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;
@@ -125108,55 +128323,68 @@
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, do not need to update the graph
project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ?
this.createConfiguredProjectWithDelayLoad(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName) :
this.createLoadAndUpdateConfiguredProject(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName);
}
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
+ // Create external project and update its graph, do not delay update since
+ // any file open operation needs all updated external projects
this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName);
var project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles);
project.updateGraph();
}
};
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;
};
ProjectService.prototype.configurePlugin = function (args) {
+ // For any projects that already have the plugin loaded, configure the plugin
this.forEachEnabledProject(function (project) { return project.onPluginConfigurationChanged(args.pluginName, args.configuration); });
+ // Also save the current configuration to pass on to any projects that are yet to be loaded.
+ // If a plugin is configured twice, only the latest configuration will be remembered.
this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || ts.createMap();
this.currentPluginConfigOverrides.set(args.pluginName, args.configuration);
};
+ /** 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;
}
@@ -125186,6 +128414,18 @@
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);
@@ -125194,7 +128434,7 @@
return false;
}
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),
@@ -125229,8 +128469,8 @@
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);
@@ -125250,7 +128490,7 @@
function allEditsBeforePos(edits, pos) {
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);
@@ -125261,7 +128501,11 @@
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;
}
@@ -125308,6 +128552,7 @@
}
catch (e) {
stop = true;
+ // ignore cancellation request
if (!(e instanceof ts.OperationCanceledException)) {
this.operationHost.logError(e, "delayed processing of request " + this.requestId);
}
@@ -125333,6 +128578,7 @@
};
return MultistepOperation;
}());
+ /** @internal */
function toEvent(eventName, body) {
return {
seq: 0,
@@ -125342,6 +128588,9 @@
};
}
server.toEvent = toEvent;
+ /**
+ * 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) {
var outputs = ts.flatMapToMutable(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); });
if (!ts.isArray(projects) && projects.symLinkedProjects) {
@@ -125362,7 +128611,8 @@
}
function combineProjectOutputWhileOpeningReferencedProjects(projects, defaultProject, action, getLocation, resultsEqual) {
var outputs = [];
- combineProjectOutputWorker(projects, defaultProject, undefined, function (_a, tryAddToTodo) {
+ combineProjectOutputWorker(projects, defaultProject,
+ /*initialLocation*/ undefined, function (_a, tryAddToTodo) {
var project = _a.project;
for (var _i = 0, _b = action(project); _i < _b.length; _i++) {
var output = _b[_i];
@@ -125370,7 +128620,8 @@
outputs.push(output);
}
}
- }, undefined);
+ },
+ /*getDefinition*/ undefined);
return outputs;
}
function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments, hostPreferences) {
@@ -125405,6 +128656,7 @@
}
for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) {
var ref = _a[_i];
+ // If it's in a mapped file, that is added to the todo list by `getMappedLocation`.
if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) {
symbolToAddTo.references.push(ref);
}
@@ -125436,9 +128688,11 @@
var toDo;
var seenProjects = ts.createMap();
forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, function (project, path) {
+ // TLocation shoud be either `DocumentPosition` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid.
var location = (initialLocation ? { fileName: path, pos: initialLocation.pos } : 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) {
@@ -125462,7 +128716,7 @@
}
function callbackProjectAndLocation(projectAndLocation, projectService, toDo, seenProjects, cb) {
if (projectAndLocation.project.getCancellationToken().isCancellationRequested())
- return undefined;
+ 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);
@@ -125499,10 +128753,10 @@
var mapsTo = project.getSourceMapper().tryGetSourcePosition(location);
return mapsTo && projectService.fileExists(server.toNormalizedPath(mapsTo.fileName)) ? mapsTo : undefined;
}
- var Session = (function () {
+ var Session = /** @class */ (function () {
function Session(opts) {
- var _a;
var _this = this;
+ var _a;
this.changeSeq = 0;
this.handlers = ts.createMapFromTemplate((_a = {},
_a[server.CommandNames.Status] = function () {
@@ -125511,15 +128765,18 @@
},
_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);
@@ -125534,31 +128791,54 @@
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.UpdateOpen] = function (request) {
+ _this.changeSeq++;
+ _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles && ts.mapIterator(ts.arrayIterator(request.arguments.openFiles), function (file) { return ({
+ fileName: file.file,
+ content: file.fileContent,
+ scriptKind: file.scriptKindName,
+ projectRootPath: file.projectRootPath
+ }); }), request.arguments.changedFiles && ts.mapIterator(ts.arrayIterator(request.arguments.changedFiles), function (file) { return ({
+ fileName: file.fileName,
+ changes: ts.mapDefinedIterator(ts.arrayReverseIterator(file.textChanges), function (change) {
+ var scriptInfo = ts.Debug.assertDefined(_this.projectService.getScriptInfo(file.fileName));
+ var start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset);
+ var end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset);
+ return start >= 0 ? { span: { start: start, length: end - start }, newText: change.newText } : undefined;
+ })
+ }); }), request.arguments.closedFiles);
+ return _this.requiredResponse(/*response*/ true);
+ },
_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 && ts.arrayIterator(request.arguments.openFiles), request.arguments.changedFiles && ts.mapIterator(ts.arrayIterator(request.arguments.changedFiles), function (file) { return ({
+ fileName: file.fileName,
+ // apply changes in reverse order
+ changes: ts.arrayReverseIterator(file.changes)
+ }); }), request.arguments.closedFiles);
+ // 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));
@@ -125567,41 +128847,42 @@
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));
@@ -125649,10 +128930,10 @@
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));
@@ -125661,10 +128942,10 @@
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));
@@ -125674,7 +128955,7 @@
},
_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));
@@ -125699,7 +128980,7 @@
},
_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) {
@@ -125717,41 +128998,41 @@
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));
@@ -125764,16 +129045,16 @@
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));
@@ -125785,25 +129066,26 @@
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[server.CommandNames.ConfigurePlugin] = function (request) {
_this.configurePlugin(request.arguments);
+ _this.doOutput(/*info*/ undefined, server.CommandNames.ConfigurePlugin, request.seq, /*success*/ true);
return _this.notRequired();
},
_a));
@@ -125846,7 +129128,7 @@
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");
@@ -125871,17 +129153,13 @@
break;
case server.ConfigFileDiagEvent:
var _c = event.data, triggerFile = _c.triggerFile, configFile = _c.configFileName, diagnostics = _c.diagnostics;
- var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, true); });
+ var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, /*includeFileName*/ true); });
this.event({
triggerFile: triggerFile,
configFile: configFile,
diagnostics: bakedDiags
}, server.ConfigFileDiagEvent);
break;
- case server.SurveyReady:
- var surveyId = event.data.surveyId;
- this.event({ surveyId: surveyId }, server.SurveyReady);
- break;
case server.ProjectLanguageServiceStateEvent: {
var eventName = server.ProjectLanguageServiceStateEvent;
this.event({
@@ -125906,8 +129184,10 @@
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
}, server.ProjectsUpdatedInBackgroundEvent);
@@ -125924,7 +129204,8 @@
msg += "\n" + server.indent(err.stack);
}
}
- if (fileRequest && this.logger.hasLevel(server.LogLevel.verbose)) {
+ if (this.logger.hasLevel(server.LogLevel.verbose)) {
+ if (fileRequest) {
try {
var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project;
var scriptInfo = project.getScriptInfoForNormalizedPath(file);
@@ -125933,7 +129214,21 @@
msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n";
}
}
- catch (_b) { }
+ catch (_b) { } // tslint:disable-line no-empty
+ }
+ if (err.message && err.message.indexOf("Could not find sourceFile:") !== -1) {
+ msg += "\n\nProjects::\n";
+ var counter_1 = 0;
+ var addProjectInfo = function (project) {
+ msg += "\nProject '" + project.projectName + "' (" + server.ProjectKind[project.projectKind] + ") " + counter_1 + "\n";
+ msg += project.filesToString(/*writeProjectFileNames*/ true);
+ msg += "\n-----------------------------------------------\n";
+ counter_1++;
+ };
+ this.projectService.externalProjects.forEach(addProjectInfo);
+ this.projectService.configuredProjects.forEach(addProjectInfo);
+ this.projectService.inferredProjects.forEach(addProjectInfo);
+ }
}
this.logger.msg(msg, server.Msg.Err);
};
@@ -125949,8 +129244,10 @@
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 = {
@@ -126011,10 +129308,11 @@
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;
@@ -126024,6 +129322,7 @@
}
var _a = checkList[index], fileName = _a.fileName, project = _a.project;
index++;
+ // 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;
@@ -126064,7 +129363,7 @@
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 () {
@@ -126097,7 +129396,7 @@
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;
@@ -126114,7 +129413,11 @@
};
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;
@@ -126175,7 +129478,7 @@
if (!unmappedDefinitionAndBoundSpan || !unmappedDefinitionAndBoundSpan.definitions) {
return {
definitions: server.emptyArray,
- textSpan: undefined
+ textSpan: undefined // TODO: GH#18217
};
}
var definitions = this.mapDefinitionInfoLocations(unmappedDefinitionAndBoundSpan.definitions, project);
@@ -126199,6 +129502,13 @@
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");
@@ -126208,7 +129518,7 @@
};
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,
@@ -126268,6 +129578,7 @@
file: fileName,
isWriteAccess: isWriteAccess,
};
+ // no need to serialize the property if it is not true
if (isInString) {
result.isInString = isInString;
}
@@ -126277,23 +129588,26 @@
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;
@@ -126333,7 +129647,7 @@
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;
@@ -126341,15 +129655,14 @@
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;
};
Session.prototype.getRenameInfo = function (args) {
var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
var position = this.getPositionInFile(args, file);
- var preferences = this.getHostPreferences();
- return project.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: preferences.allowRenameOfImportPath });
+ return project.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath });
};
Session.prototype.getProjects = function (args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) {
var projects;
@@ -126373,12 +129686,13 @@
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 (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) {
this.projectService.logErrorForScriptInfoNotFound(args.file);
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) {
@@ -126394,11 +129708,11 @@
var file = server.toNormalizedPath(args.file);
var position = this.getPositionInFile(args, file);
var projects = this.getProjects(args);
- var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, this.getHostPreferences());
+ var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, this.getPreferences(file));
if (!simplifiedResult)
return locations;
var defaultProject = this.getDefaultProject(args);
- var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getHostPreferences().allowRenameOfImportPath }), ts.Debug.assertDefined(this.projectService.getScriptInfo(file)));
+ var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath }), ts.Debug.assertDefined(this.projectService.getScriptInfo(file)));
return { info: renameInfo, locs: this.toSpanGroups(locations) };
};
Session.prototype.mapRenameInfo = function (info, scriptInfo) {
@@ -126454,8 +129768,12 @@
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);
@@ -126468,6 +129786,8 @@
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.tryGetDefaultProjectForFile(file);
if (!project) {
@@ -126475,7 +129795,7 @@
}
return {
file: file,
- languageService: project.getLanguageService(false)
+ languageService: project.getLanguageService(/*ensureSynchronized*/ false)
};
};
Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName) {
@@ -126568,6 +129888,7 @@
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;
@@ -126577,7 +129898,7 @@
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;
@@ -126587,7 +129908,7 @@
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;
@@ -126595,6 +129916,12 @@
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.getAbsolutePositionAndLineText(args.line), lineText = _b.lineText, absolutePosition = _b.absolutePosition;
if (lineText && lineText.search("\\S") < 0) {
@@ -126606,12 +129933,13 @@
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({
@@ -126640,17 +129968,18 @@
var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, server.convertUserPreferences(this.getPreferences(file)), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions }));
if (completions === undefined)
return undefined;
- if (kind === "completions-full")
+ 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_1 = 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_1, 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") {
+ if (kind === "completions" /* Completions */) {
if (completions.metadata)
entries.metadata = completions.metadata;
return entries;
@@ -126674,7 +130003,7 @@
};
Session.prototype.getCompileOnSaveAffectedFileList = function (args) {
var _this = this;
- var projects = this.getProjects(args, true, true);
+ var projects = this.getProjects(args, /*getScriptInfoEnsuringProjectsUptoDate*/ true, /*ignoreNoProjectError*/ true);
var info = this.projectService.getScriptInfo(args.file);
if (!info) {
return server.emptyArray;
@@ -126752,10 +130081,10 @@
var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
if (start >= 0) {
this.changeSeq++;
- this.projectService.applyChangesToFile(scriptInfo, [{
+ this.projectService.applyChangesToFile(scriptInfo, ts.singleIterator({
span: { start: start, length: end - start },
- newText: args.insertString
- }]);
+ newText: args.insertString // TODO: GH#18217
+ }));
}
};
Session.prototype.reload = function (args, reqSeq) {
@@ -126764,8 +130093,9 @@
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);
}
}
};
@@ -126863,7 +130193,7 @@
}
else {
return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(args), this.getDefaultProject(args), function (project) {
- return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, undefined, project.isNonTsProject());
+ return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*fileName*/ undefined, /*excludeDts*/ project.isNonTsProject());
}, documentSpanLocation, navigateToItemIsEqualTo);
}
function navigateToItemIsEqualTo(a, b) {
@@ -126975,7 +130305,7 @@
}
};
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 _b = this.getFileAndProject(command), file = _b.file, project = _b.project;
@@ -126990,6 +130320,7 @@
}
else {
startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset);
+ // save the result so we don't always recompute
args.startPosition = startPosition;
}
if (args.endPosition !== undefined) {
@@ -127016,7 +130347,7 @@
Session.prototype.mapTextChangeToCodeEdit = function (textChanges) {
var scriptInfo = this.projectService.getScriptInfoOrConfig(textChanges.fileName);
if (!!textChanges.isNewFile === !!scriptInfo) {
- if (!scriptInfo) {
+ if (!scriptInfo) { // and !isNewFile
this.projectService.logErrorForScriptInfoNotFound(textChanges.fileName);
}
ts.Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo }));
@@ -127048,14 +130379,16 @@
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 = [];
@@ -127068,9 +130401,9 @@
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 {
@@ -127084,7 +130417,9 @@
}
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.configurePlugin = function (args) {
this.projectService.configurePlugin(args);
@@ -127113,7 +130448,7 @@
};
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) {
@@ -127132,7 +130467,7 @@
}
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 };
}
};
@@ -127161,19 +130496,22 @@
}
}
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.logErrorWorker(err, message, relevantFile);
- 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) {
@@ -127209,6 +130547,7 @@
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;
@@ -127230,6 +130569,7 @@
}
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
+/*@internal*/
var ts;
(function (ts) {
var server;
@@ -127244,12 +130584,12 @@
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();
@@ -127295,6 +130635,7 @@
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];
@@ -127329,6 +130670,7 @@
}
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();
@@ -127337,15 +130679,20 @@
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;
}
@@ -127358,14 +130705,14 @@
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 {
@@ -127374,8 +130721,8 @@
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);
@@ -127388,11 +130735,11 @@
}
}
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 {
@@ -127403,9 +130750,9 @@
}
}
break;
- case 5:
+ case 5 /* PostEnd */:
this.goSubtree = false;
- if (this.state !== 1) {
+ if (this.state !== 1 /* Start */) {
currentNode.add(lineCollection);
}
break;
@@ -127414,21 +130761,24 @@
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;
@@ -127439,11 +130789,11 @@
};
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) {
@@ -127455,6 +130805,7 @@
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 ||
@@ -127505,7 +130856,7 @@
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());
@@ -127538,7 +130889,7 @@
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;
@@ -127564,8 +130915,9 @@
};
return LineIndexSnapshot;
}());
- var LineIndex = (function () {
+ var LineIndex = /** @class */ (function () {
function LineIndex() {
+ // set this to true to check each edit for accuracy
this.checkEdits = false;
}
LineIndex.prototype.absolutePositionOfStartOfLine = function (oneBasedLine) {
@@ -127640,12 +130992,12 @@
};
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;
@@ -127656,6 +131008,7 @@
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) {
@@ -127668,10 +131021,13 @@
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;
}
}
@@ -127719,7 +131075,7 @@
return LineIndex;
}());
server.LineIndex = LineIndex;
- var LineNode = (function () {
+ var LineNode = /** @class */ (function () {
function LineNode(children) {
if (children === void 0) { children = []; }
this.children = children;
@@ -127762,22 +131118,26 @@
}
};
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);
@@ -127785,7 +131145,7 @@
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;
@@ -127793,22 +131153,26 @@
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++) {
@@ -127826,9 +131190,15 @@
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];
@@ -127878,6 +131248,7 @@
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();
@@ -127926,6 +131297,7 @@
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);
@@ -127938,7 +131310,7 @@
};
return LineNode;
}());
- var LineLeaf = (function () {
+ var LineLeaf = /** @class */ (function () {
function LineLeaf(text) {
this.text = text;
}
@@ -127958,7 +131330,6 @@
}());
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
-//# sourceMappingURL=server.js.map
// tslint:disable no-unnecessary-type-assertion (TODO: tslint can't find node types)
var ts;
(function (ts) {
@@ -127976,7 +131347,7 @@
process.env.USERPROFILE ||
(process.env.HOMEDRIVE && process.env.HOMEPATH && ts.normalizeSlashes(process.env.HOMEDRIVE + process.env.HOMEPATH)) ||
os.tmpdir();
- return ts.combinePaths(ts.combinePaths(ts.normalizeSlashes(basePath), "Microsoft/TypeScript"), ts.versionMajorMinor);
+ return ts.combinePaths(ts.combinePaths(ts.normalizeSlashes(basePath), "Microsoft/TypeScript"), ts.version);
}
case "openbsd":
case "freebsd":
@@ -127984,7 +131355,7 @@
case "linux":
case "android": {
var cacheLocation = getNonWindowsCacheLocation(process.platform === "darwin");
- return ts.combinePaths(ts.combinePaths(cacheLocation, "typescript"), ts.versionMajorMinor);
+ return ts.combinePaths(ts.combinePaths(cacheLocation, "typescript"), ts.version);
}
default:
return ts.Debug.fail("unsupported platform '" + process.platform + "'");
@@ -128096,7 +131467,7 @@
return Logger;
}());
var NodeTypingsInstaller = /** @class */ (function () {
- function NodeTypingsInstaller(telemetryEnabled, logger, host, globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, event) {
+ function NodeTypingsInstaller(telemetryEnabled, logger, host, globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, event) {
this.telemetryEnabled = telemetryEnabled;
this.logger = logger;
this.host = host;
@@ -128104,6 +131475,7 @@
this.typingSafeListLocation = typingSafeListLocation;
this.typesMapLocation = typesMapLocation;
this.npmLocation = npmLocation;
+ this.validateDefaultNpmLocation = validateDefaultNpmLocation;
this.event = event;
this.activeRequestCount = 0;
this.requestQueue = [];
@@ -128160,6 +131532,9 @@
if (this.npmLocation) {
args.push(server.Arguments.NpmLocation, this.npmLocation);
}
+ if (this.validateDefaultNpmLocation) {
+ args.push(server.Arguments.ValidateDefaultNpmLocation);
+ }
var execArgv = [];
for (var _i = 0, _a = process.execArgv; _i < _a.length; _i++) {
var arg = _a[_i];
@@ -128344,7 +131719,7 @@
var host = sys;
var typingsInstaller = disableAutomaticTypingAcquisition
? undefined
- : new NodeTypingsInstaller(telemetryEnabled, logger, host, getGlobalTypingsCacheLocation(), typingSafeListLocation, typesMapLocation, npmLocation, event);
+ : new NodeTypingsInstaller(telemetryEnabled, logger, host, getGlobalTypingsCacheLocation(), typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, event);
_this = _super.call(this, {
host: host,
cancellationToken: cancellationToken,
@@ -128531,6 +131906,7 @@
// stat due to inconsistencies of fs.watch
// and efficiency of stat on modern filesystems
function startWatchTimer() {
+ // tslint:disable-next-line:ban
setInterval(function () {
var count = 0;
var nextToCheck = nextFileToCheck;
@@ -128738,6 +132114,7 @@
var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation); // TODO: GH#18217
var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation) || ts.combinePaths(ts.getDirectoryPath(sys.getExecutingFilePath()), "typesMap.json");
var npmLocation = server.findArgument(server.Arguments.NpmLocation);
+ var validateDefaultNpmLocation = server.hasArgument(server.Arguments.ValidateDefaultNpmLocation);
function parseStringArray(argName) {
var arg = server.findArgument(argName);
if (arg === undefined) {

lib/tsserverlibrary.d.ts

@@ -14,7 +14,7 @@
***************************************************************************** */
declare namespace ts {
- const versionMajorMinor = "3.2";
+ const versionMajorMinor = "3.4";
/** The version of the TypeScript compiler release */
const version: string;
}
@@ -355,40 +355,45 @@
ShorthandPropertyAssignment = 276,
SpreadAssignment = 277,
EnumMember = 278,
- SourceFile = 279,
- Bundle = 280,
- UnparsedSource = 281,
- InputFiles = 282,
- JSDocTypeExpression = 283,
- JSDocAllType = 284,
- JSDocUnknownType = 285,
- JSDocNullableType = 286,
- JSDocNonNullableType = 287,
- JSDocOptionalType = 288,
- JSDocFunctionType = 289,
- JSDocVariadicType = 290,
- JSDocComment = 291,
- JSDocTypeLiteral = 292,
- JSDocSignature = 293,
- JSDocTag = 294,
- JSDocAugmentsTag = 295,
- JSDocClassTag = 296,
- JSDocCallbackTag = 297,
- JSDocEnumTag = 298,
- JSDocParameterTag = 299,
- JSDocReturnTag = 300,
- JSDocThisTag = 301,
- JSDocTypeTag = 302,
- JSDocTemplateTag = 303,
- JSDocTypedefTag = 304,
- JSDocPropertyTag = 305,
- SyntaxList = 306,
- NotEmittedStatement = 307,
- PartiallyEmittedExpression = 308,
- CommaListExpression = 309,
- MergeDeclarationMarker = 310,
- EndOfDeclarationMarker = 311,
- Count = 312,
+ UnparsedPrologue = 279,
+ UnparsedPrepend = 280,
+ UnparsedText = 281,
+ UnparsedInternalText = 282,
+ UnparsedSyntheticReference = 283,
+ SourceFile = 284,
+ Bundle = 285,
+ UnparsedSource = 286,
+ InputFiles = 287,
+ JSDocTypeExpression = 288,
+ JSDocAllType = 289,
+ JSDocUnknownType = 290,
+ JSDocNullableType = 291,
+ JSDocNonNullableType = 292,
+ JSDocOptionalType = 293,
+ JSDocFunctionType = 294,
+ JSDocVariadicType = 295,
+ JSDocComment = 296,
+ JSDocTypeLiteral = 297,
+ JSDocSignature = 298,
+ JSDocTag = 299,
+ JSDocAugmentsTag = 300,
+ JSDocClassTag = 301,
+ JSDocCallbackTag = 302,
+ JSDocEnumTag = 303,
+ JSDocParameterTag = 304,
+ JSDocReturnTag = 305,
+ JSDocThisTag = 306,
+ JSDocTypeTag = 307,
+ JSDocTemplateTag = 308,
+ JSDocTypedefTag = 309,
+ JSDocPropertyTag = 310,
+ SyntaxList = 311,
+ NotEmittedStatement = 312,
+ PartiallyEmittedExpression = 313,
+ CommaListExpression = 314,
+ MergeDeclarationMarker = 315,
+ EndOfDeclarationMarker = 316,
+ Count = 317,
FirstAssignment = 59,
LastAssignment = 71,
FirstCompoundAssignment = 60,
@@ -414,10 +419,10 @@
FirstBinaryOperator = 28,
LastBinaryOperator = 71,
FirstNode = 148,
- FirstJSDocNode = 283,
- LastJSDocNode = 305,
- FirstJSDocTagNode = 294,
- LastJSDocTagNode = 305
+ FirstJSDocNode = 288,
+ LastJSDocNode = 310,
+ FirstJSDocTagNode = 299,
+ LastJSDocTagNode = 310,
}
enum NodeFlags {
None = 0,
@@ -446,7 +451,7 @@
ReachabilityCheckFlags = 384,
ReachabilityAndEmitFlags = 1408,
ContextFlags = 12679168,
- TypeExcludesFlags = 20480
+ TypeExcludesFlags = 20480,
}
enum ModifierFlags {
None = 0,
@@ -814,7 +819,7 @@
}
interface TypeOperatorNode extends TypeNode {
kind: SyntaxKind.TypeOperator;
- operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword;
+ operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword;
type: TypeNode;
}
interface IndexedAccessTypeNode extends TypeNode {
@@ -997,6 +1002,14 @@
interface NoSubstitutionTemplateLiteral extends LiteralExpression {
kind: SyntaxKind.NoSubstitutionTemplateLiteral;
}
+ enum TokenFlags {
+ None = 0,
+ Scientific = 16,
+ Octal = 32,
+ HexSpecifier = 64,
+ BinarySpecifier = 128,
+ OctalSpecifier = 256,
+ }
interface NumericLiteral extends LiteralExpression {
kind: SyntaxKind.NumericLiteral;
}
@@ -1190,9 +1203,9 @@
dotDotDotToken?: Token<SyntaxKind.DotDotDotToken>;
expression?: Expression;
}
- interface JsxText extends Node {
+ interface JsxText extends LiteralLikeNode {
kind: SyntaxKind.JsxText;
- containsOnlyWhiteSpaces: boolean;
+ containsOnlyTriviaWhiteSpaces: boolean;
parent: JsxElement;
}
type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment;
@@ -1726,18 +1739,55 @@
}
interface InputFiles extends Node {
kind: SyntaxKind.InputFiles;
+ javascriptPath?: string;
javascriptText: string;
javascriptMapPath?: string;
javascriptMapText?: string;
+ declarationPath?: string;
declarationText: string;
declarationMapPath?: string;
declarationMapText?: string;
}
interface UnparsedSource extends Node {
kind: SyntaxKind.UnparsedSource;
+ fileName: string;
text: string;
+ prologues: ReadonlyArray<UnparsedPrologue>;
+ helpers: ReadonlyArray<UnscopedEmitHelper> | undefined;
+ referencedFiles: ReadonlyArray<FileReference>;
+ typeReferenceDirectives: ReadonlyArray<string> | undefined;
+ libReferenceDirectives: ReadonlyArray<FileReference>;
+ hasNoDefaultLib?: boolean;
sourceMapPath?: string;
sourceMapText?: string;
+ syntheticReferences?: ReadonlyArray<UnparsedSyntheticReference>;
+ texts: ReadonlyArray<UnparsedSourceText>;
+ }
+ type UnparsedSourceText = UnparsedPrepend | UnparsedTextLike;
+ type UnparsedNode = UnparsedPrologue | UnparsedSourceText | UnparsedSyntheticReference;
+ interface UnparsedSection extends Node {
+ kind: SyntaxKind;
+ data?: string;
+ parent: UnparsedSource;
+ }
+ interface UnparsedPrologue extends UnparsedSection {
+ kind: SyntaxKind.UnparsedPrologue;
+ data: string;
+ parent: UnparsedSource;
+ }
+ interface UnparsedPrepend extends UnparsedSection {
+ kind: SyntaxKind.UnparsedPrepend;
+ data: string;
+ parent: UnparsedSource;
+ texts: ReadonlyArray<UnparsedTextLike>;
+ }
+ interface UnparsedTextLike extends UnparsedSection {
+ kind: SyntaxKind.UnparsedText | SyntaxKind.UnparsedInternalText;
+ parent: UnparsedSource;
+ }
+ interface UnparsedSyntheticReference extends UnparsedSection {
+ kind: SyntaxKind.UnparsedSyntheticReference;
+ parent: UnparsedSource;
}
interface JsonSourceFile extends SourceFile {
statements: NodeArray<JsonObjectExpressionStatement>;
@@ -1778,7 +1828,7 @@
type ResolvedConfigFileName = string & {
_isResolvedConfigFileName: never;
};
- type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles?: ReadonlyArray<SourceFile>) => void;
+ type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: ReadonlyArray<SourceFile>) => void;
class OperationCanceledException {
}
interface CancellationToken {
@@ -2011,7 +2061,7 @@
WriteTypeParametersOrArguments = 1,
UseOnlyExternalAliasing = 2,
AllowAnyNodeKind = 4,
- UseAliasDefinedOutsideCurrentScope = 8
+ UseAliasDefinedOutsideCurrentScope = 8,
}
enum TypePredicateKind {
This = 0,
@@ -2089,7 +2139,7 @@
ExportHasLocal = 944,
BlockScoped = 418,
PropertyOrAccessor = 98308,
- ClassMember = 106500
+ ClassMember = 106500,
}
interface Symbol {
flags: SymbolFlags;
@@ -2197,7 +2247,7 @@
Instantiable = 63176704,
StructuredOrInstantiable = 66846720,
Narrowable = 133970943,
- NotUnionOrUnit = 67637251
+ NotUnionOrUnit = 67637251,
}
type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
interface Type {
@@ -2214,6 +2264,7 @@
}
interface UniqueESSymbolType extends Type {
symbol: Symbol;
+ escapedName: __String;
}
interface StringLiteralType extends LiteralType {
value: string;
@@ -2243,7 +2294,7 @@
MarkerType = 8192,
JSLiteral = 16384,
FreshLiteral = 32768,
- ClassOrInterface = 3
+ ClassOrInterface = 3,
}
interface ObjectType extends Type {
objectFlags: ObjectFlags;
@@ -2282,6 +2333,7 @@
interface TupleType extends GenericType {
minLength: number;
hasRestElement: boolean;
+ readonly: boolean;
associatedNames?: __String[];
}
interface TupleTypeReference extends TypeReference {
@@ -2330,8 +2382,8 @@
root: ConditionalRoot;
checkType: Type;
extendsType: Type;
- resolvedTrueType?: Type;
- resolvedFalseType?: Type;
+ trueType: Type;
+ falseType: Type;
}
interface SubstitutionType extends InstantiableType {
typeVariable: TypeVariable;
@@ -2490,6 +2542,8 @@
reactNamespace?: string;
jsxFactory?: string;
composite?: boolean;
+ incremental?: boolean;
+ tsBuildInfoFile?: string;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -2566,9 +2620,10 @@
ES2016 = 3,
ES2017 = 4,
ES2018 = 5,
- ESNext = 6,
+ ES2019 = 6,
+ ESNext = 7,
JSON = 100,
- Latest = 6
+ Latest = 7
}
enum LanguageVariant {
Standard = 0,
@@ -2665,7 +2720,8 @@
Dts = ".d.ts",
Js = ".js",
Jsx = ".jsx",
- Json = ".json"
+ Json = ".json",
+ TsBuildInfo = ".tsbuildinfo"
}
interface ResolvedModuleWithFailedLookupLocations {
readonly resolvedModule: ResolvedModuleFull | undefined;
@@ -2689,7 +2745,6 @@
getDefaultLibLocation?(): string;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
- getDirectories(path: string): string[];
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
@@ -2739,7 +2794,7 @@
NoHoisting = 2097152,
HasEndOfDeclarationMarker = 4194304,
Iterator = 8388608,
- NoAsciiEscaping = 16777216
+ NoAsciiEscaping = 16777216,
}
interface EmitHelper {
readonly name: string;
@@ -2747,6 +2802,10 @@
readonly text: string | ((node: EmitHelperUniqueNameCallback) => string);
readonly priority?: number;
}
+ interface UnscopedEmitHelper extends EmitHelper {
+ readonly scoped: false;
+ readonly text: string;
+ }
type EmitHelperUniqueNameCallback = (name: string) => string;
enum EmitHint {
SourceFile = 0,
@@ -3006,13 +3065,14 @@
}
interface UserPreferences {
readonly disableSuggestions?: boolean;
- readonly quotePreference?: "double" | "single";
+ readonly quotePreference?: "auto" | "double" | "single";
readonly includeCompletionsForModuleExports?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
readonly importModuleSpecifierEnding?: "minimal" | "index" | "js";
readonly allowTextChangesInNewFiles?: boolean;
+ readonly providePrefixAndSuffixTextForRename?: boolean;
}
/** Represents a bigint literal value without requiring bigint support */
interface PseudoBigInt {
@@ -3097,6 +3157,7 @@
scanJsxIdentifier(): SyntaxKind;
scanJsxAttributeValue(): SyntaxKind;
reScanJsxToken(): JsxTokenSyntaxKind;
+ reScanLessThanToken(): SyntaxKind;
scanJsxToken(): JsxTokenSyntaxKind;
scanJSDocToken(): JsDocSyntaxKind;
scan(): SyntaxKind;
@@ -3354,6 +3415,7 @@
function isNewExpression(node: Node): node is NewExpression;
function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression;
function isTypeAssertion(node: Node): node is TypeAssertion;
+ function isConstTypeReference(node: Node): boolean;
function isParenthesizedExpression(node: Node): node is ParenthesizedExpression;
function skipPartiallyEmittedExpressions(node: Expression): Expression;
function skipPartiallyEmittedExpressions(node: Node): Node;
@@ -3443,6 +3505,9 @@
function isSourceFile(node: Node): node is SourceFile;
function isBundle(node: Node): node is Bundle;
function isUnparsedSource(node: Node): node is UnparsedSource;
+ function isUnparsedPrepend(node: Node): node is UnparsedPrepend;
+ function isUnparsedTextLike(node: Node): node is UnparsedTextLike;
+ function isUnparsedNode(node: Node): node is UnparsedNode;
function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression;
function isJSDocAllType(node: JSDocAllType): node is JSDocAllType;
function isJSDocUnknownType(node: Node): node is JSDocUnknownType;
@@ -3662,7 +3727,7 @@
function createLiteral(value: number | PseudoBigInt): NumericLiteral;
function createLiteral(value: boolean): BooleanLiteral;
function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression;
- function createNumericLiteral(value: string): NumericLiteral;
+ function createNumericLiteral(value: string, numericLiteralFlags?: TokenFlags): NumericLiteral;
function createBigIntLiteral(value: string): BigIntLiteral;
function createStringLiteral(text: string): StringLiteral;
function createRegularExpressionLiteral(text: string): RegularExpressionLiteral;
@@ -3754,7 +3819,7 @@
function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode;
function createThisTypeNode(): ThisTypeNode;
function createTypeOperatorNode(type: TypeNode): TypeOperatorNode;
- function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword, type: TypeNode): TypeOperatorNode;
+ function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword, type: TypeNode): TypeOperatorNode;
function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode;
function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
@@ -3927,6 +3992,10 @@
function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement;
function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement;
function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray<JsxChild>, closingFragment: JsxClosingFragment): JsxFragment;
+ function createJsxText(text: string, containsOnlyTriviaWhiteSpaces?: boolean): JsxText;
+ function updateJsxText(node: JsxText, text: string, containsOnlyTriviaWhiteSpaces?: boolean): JsxText;
+ function createJsxOpeningFragment(): JsxOpeningFragment;
+ function createJsxJsxClosingFragment(): JsxClosingFragment;
function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: ReadonlyArray<JsxChild>, closingFragment: JsxClosingFragment): JsxFragment;
function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute;
function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute;
@@ -3978,9 +4047,11 @@
function updateCommaList(node: CommaListExpression, elements: ReadonlyArray<Expression>): CommaListExpression;
function createBundle(sourceFiles: ReadonlyArray<SourceFile>, prepends?: ReadonlyArray<UnparsedSource | InputFiles>): Bundle;
function createUnparsedSourceFile(text: string): UnparsedSource;
+ function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts", stripInternal?: boolean): UnparsedSource;
function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource;
- function createInputFiles(javascript: string, declaration: string): InputFiles;
- function createInputFiles(javascript: string, declaration: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): InputFiles;
+ function createInputFiles(javascriptText: string, declarationText: string): InputFiles;
+ function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined, buildInfoPath: string | undefined): InputFiles;
+ function createInputFiles(javascriptText: string, declarationText: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): InputFiles;
function updateBundle(node: Bundle, sourceFiles: ReadonlyArray<SourceFile>, prepends?: ReadonlyArray<UnparsedSource>): Bundle;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray<Statement>): CallExpression;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray<Statement>, param: ParameterDeclaration, paramValue: Expression): CallExpression;
@@ -4279,6 +4350,10 @@
*/
getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray<Diagnostic>;
/**
+ * Get the declaration diagnostics, for all source files if source file is not supplied
+ */
+ getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray<DiagnosticWithLocation>;
+ /**
* Get all the dependencies of the file
*/
getAllDependencies(sourceFile: SourceFile): ReadonlyArray<string>;
@@ -4364,13 +4439,11 @@
/** If provided, will be used to reset existing delayed compilation */
clearTimeout?(timeoutId: any): void;
}
- interface WatchCompilerHost<T extends BuilderProgram> extends WatchHost {
+ interface ProgramHost<T extends BuilderProgram> {
/**
* Used to create the program when need for program creation or recreation detected
*/
createProgram: CreateProgram<T>;
- /** If provided, callback to invoke after every new program creation */
- afterProgramCreate?(program: T): void;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
getCurrentDirectory(): string;
@@ -4404,6 +4477,10 @@
/** If provided, used to resolve type reference directives, otherwise typescript's default resolution */
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[];
}
+ interface WatchCompilerHost<T extends BuilderProgram> extends ProgramHost<T>, WatchHost {
+ /** If provided, callback to invoke after every new program creation */
+ afterProgramCreate?(program: T): void;
+ }
/**
* Host to create watch with root files and options
*/
@@ -4706,8 +4783,8 @@
getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined;
getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined;
getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined;
- getRenameInfo(fileName: string, position: number): RenameInfo;
- findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ReadonlyArray<RenameLocation> | undefined;
+ getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): RenameInfo;
+ findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): ReadonlyArray<RenameLocation> | undefined;
getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray<DefinitionInfo> | undefined;
getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined;
getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray<DefinitionInfo> | undefined;
@@ -5150,6 +5227,9 @@
canRename: false;
localizedErrorMessage: string;
}
+ interface RenameInfoOptions {
+ readonly allowRenameOfImportPath?: boolean;
+ }
interface SignatureHelpParameter {
name: string;
documentation: SymbolDisplayPart[];
@@ -5693,6 +5773,7 @@
OpenExternalProject = "openExternalProject",
OpenExternalProjects = "openExternalProjects",
CloseExternalProject = "closeExternalProject",
+ UpdateOpen = "updateOpen",
GetOutliningSpans = "getOutliningSpans",
TodoComments = "todoComments",
Indentation = "indentation",
@@ -6667,6 +6748,8 @@
command: CommandTypes.ConfigurePlugin;
arguments: ConfigurePluginRequestArguments;
}
+ interface ConfigurePluginResponse extends Response {
+ }
/**
* Information found in an "open" request.
*/
@@ -6762,6 +6845,30 @@
interface CloseExternalProjectResponse extends Response {
}
/**
+ * Request to synchronize list of open files with the client
+ */
+ interface UpdateOpenRequest extends Request {
+ command: CommandTypes.UpdateOpen;
+ arguments: UpdateOpenRequestArgs;
+ }
+ /**
+ * Arguments to UpdateOpenRequest
+ */
+ interface UpdateOpenRequestArgs {
+ /**
+ * List of newly open files
+ */
+ openFiles?: OpenRequestArgs[];
+ /**
+ * List of open files files that were changes
+ */
+ changedFiles?: FileCodeEdits[];
+ /**
+ * List of files that were closed
+ */
+ 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.
@@ -7909,7 +8016,7 @@
}
interface UserPreferences {
readonly disableSuggestions?: boolean;
- readonly quotePreference?: "double" | "single";
+ readonly quotePreference?: "auto" | "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.`.
@@ -7923,6 +8030,8 @@
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
readonly allowTextChangesInNewFiles?: boolean;
readonly lazyConfiguredProjectsFromExternalProject?: boolean;
+ readonly providePrefixAndSuffixTextForRename?: boolean;
+ readonly allowRenameOfImportPath?: boolean;
}
interface CompilerOptions {
allowJs?: boolean;
@@ -8326,7 +8435,7 @@
excludedFiles: ReadonlyArray<NormalizedPath>;
private typeAcquisition;
updateGraph(): boolean;
- getExcludedFiles(): ReadonlyArray<NormalizedPath>;
+ getExcludedFiles(): readonly NormalizedPath[];
getTypeAcquisition(): TypeAcquisition;
setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void;
}
@@ -8336,7 +8445,6 @@
const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground";
const ProjectLoadingStartEvent = "projectLoadingStart";
const ProjectLoadingFinishEvent = "projectLoadingFinish";
- const SurveyReady = "surveyReady";
const LargeFileReferencedEvent = "largeFileReferenced";
const ConfigFileDiagEvent = "configFileDiag";
const ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
@@ -8361,12 +8469,6 @@
project: Project;
};
}
- interface SurveyReady {
- eventName: typeof SurveyReady;
- data: {
- surveyId: string;
- };
- }
interface LargeFileReferencedEvent {
eventName: typeof LargeFileReferencedEvent;
data: {
@@ -8451,7 +8553,7 @@
interface OpenFileInfo {
readonly checkJs: boolean;
}
- type ProjectServiceEvent = LargeFileReferencedEvent | SurveyReady | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent;
+ type ProjectServiceEvent = LargeFileReferencedEvent | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent;
type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void;
interface SafeList {
[name: string]: {
@@ -8497,10 +8599,6 @@
syntaxOnly?: boolean;
}
class ProjectService {
- /**
- * Container of all known scripts
- */
- private readonly filenameToScriptInfo;
private readonly scriptInfoInNodeModulesWatchers;
/**
* Contains all the deleted script info's version information so that
@@ -8572,8 +8670,6 @@
readonly syntaxOnly?: boolean;
/** Tracks projects that we have already sent telemetry for. */
private readonly seenProjects;
- /** Tracks projects that we have already sent survey events for. */
- private readonly seenSurveyProjects;
constructor(opts: ProjectServiceOptions);
toPath(fileName: string): Path;
private loadTypesMap;
@@ -8599,6 +8695,9 @@
getHostFormatCodeOptions(): FormatCodeSettings;
getHostPreferences(): protocol.UserPreferences;
private onSourceFileChanged;
+ private handleSourceMapProjects;
+ private delayUpdateSourceInfoProjects;
+ private delayUpdateProjectsOfScriptInfoPath;
private handleDeletedFile;
private onConfigChangedForConfiguredProject;
/**
@@ -8608,6 +8707,7 @@
*/
private onConfigFileChangeForOpenScriptInfo;
private removeProject;
+ private assignOrphanScriptInfosToInferredProject;
/**
* Remove this file from the set of open, non-configured files.
* @param info The file that has been closed or newly configured
@@ -8689,6 +8789,8 @@
*/
getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined;
getScriptInfoForPath(fileName: Path): ScriptInfo | undefined;
+ private addSourceInfoToSourceMap;
+ private addMissingSourceMapFile;
setHostConfiguration(args: protocol.ConfigureRequestArguments): void;
closeLog(): void;
/**
@@ -8724,8 +8826,12 @@
*/
openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: string): OpenConfiguredProjectResult;
private findExternalProjectContainingOpenScriptInfo;
+ private getOrCreateOpenScriptInfo;
+ private assignProjectToOpenedScriptInfo;
+ private cleanupAfterOpeningFile;
openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult;
private removeOrphanConfiguredProjects;
+ private removeOrphanScriptInfos;
private telemetryOnOpenFile;
/**
* Close file whose contents is managed by the client

lib/tsserverlibrary.js

@@ -82,9 +82,9 @@
(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.3";
+ ts.versionMajorMinor = "3.4";
/** The version of the TypeScript compiler release */
- ts.version = ts.versionMajorMinor + ".4000";
+ ts.version = ts.versionMajorMinor + ".5";
})(ts || (ts = {}));
(function (ts) {
/* @internal */
@@ -140,19 +140,25 @@
// Keep the class inside a function so it doesn't get compiled if it's not used.
function shimMap() {
var MapIterator = /** @class */ (function () {
- function MapIterator(data, selector) {
- this.index = 0;
- this.data = data;
+ function MapIterator(currentEntry, selector) {
+ this.currentEntry = currentEntry;
this.selector = selector;
- this.keys = Object.keys(data);
}
MapIterator.prototype.next = function () {
- var index = this.index;
- if (index < this.keys.length) {
- this.index++;
- return { value: this.selector(this.data, this.keys[index]), done: false };
+ // Navigate to the next entry.
+ while (this.currentEntry) {
+ var skipNext = !!this.currentEntry.skipNext;
+ this.currentEntry = this.currentEntry.nextEntry;
+ if (!skipNext) {
+ break;
+ }
}
+ if (this.currentEntry) {
+ return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false };
+ }
+ else {
return { value: undefined, done: true };
+ }
};
return MapIterator;
}());
@@ -160,15 +166,36 @@
function class_1() {
this.data = createDictionaryObject();
this.size = 0;
+ // Create a first (stub) map entry that will not contain a key
+ // and value but serves as starting point for iterators.
+ this.firstEntry = {};
+ // When the map is empty, the last entry is the same as the
+ // first one.
+ this.lastEntry = this.firstEntry;
}
class_1.prototype.get = function (key) {
- return this.data[key];
+ var entry = this.data[key];
+ return entry && entry.value;
};
class_1.prototype.set = function (key, value) {
if (!this.has(key)) {
this.size++;
+ // Create a new entry that will be appended at the
+ // end of the linked list.
+ var newEntry = {
+ key: key,
+ value: value
+ };
+ this.data[key] = newEntry;
+ // Adjust the references.
+ var previousLastEntry = this.lastEntry;
+ previousLastEntry.nextEntry = newEntry;
+ newEntry.previousEntry = previousLastEntry;
+ this.lastEntry = newEntry;
+ }
+ else {
+ this.data[key].value = value;
}
- this.data[key] = value;
return this;
};
class_1.prototype.has = function (key) {
@@ -178,7 +205,28 @@
class_1.prototype.delete = function (key) {
if (this.has(key)) {
this.size--;
+ var entry = this.data[key];
delete this.data[key];
+ // Adjust the linked list references of the neighbor entries.
+ var previousEntry = entry.previousEntry;
+ previousEntry.nextEntry = entry.nextEntry;
+ if (entry.nextEntry) {
+ entry.nextEntry.previousEntry = previousEntry;
+ }
+ // When the deleted entry was the last one, we need to
+ // adust the lastEntry reference.
+ if (this.lastEntry === entry) {
+ this.lastEntry = previousEntry;
+ }
+ // Adjust the forward reference of the deleted entry
+ // in case an iterator still references it. This allows us
+ // to throw away the entry, but when an active iterator
+ // (which points to the current entry) continues, it will
+ // navigate to the entry that originally came before the
+ // current one and skip it.
+ entry.previousEntry = undefined;
+ entry.nextEntry = previousEntry;
+ entry.skipNext = true;
return true;
}
return false;
@@ -186,24 +234,46 @@
class_1.prototype.clear = function () {
this.data = createDictionaryObject();
this.size = 0;
+ // Reset the linked list. Note that we must adjust the forward
+ // references of the deleted entries to ensure iterators stuck
+ // in the middle of the list don't continue with deleted entries,
+ // but can continue with new entries added after the clear()
+ // operation.
+ var firstEntry = this.firstEntry;
+ var currentEntry = firstEntry.nextEntry;
+ while (currentEntry) {
+ var nextEntry = currentEntry.nextEntry;
+ currentEntry.previousEntry = undefined;
+ currentEntry.nextEntry = firstEntry;
+ currentEntry.skipNext = true;
+ currentEntry = nextEntry;
+ }
+ firstEntry.nextEntry = undefined;
+ this.lastEntry = firstEntry;
};
class_1.prototype.keys = function () {
- return new MapIterator(this.data, function (_data, key) { return key; });
+ return new MapIterator(this.firstEntry, function (key) { return key; });
};
class_1.prototype.values = function () {
- return new MapIterator(this.data, function (data, key) { return data[key]; });
+ return new MapIterator(this.firstEntry, function (_key, value) { return value; });
};
class_1.prototype.entries = function () {
- return new MapIterator(this.data, function (data, key) { return [key, data[key]]; });
+ return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; });
};
class_1.prototype.forEach = function (action) {
- for (var key in this.data) {
- action(this.data[key], key);
+ var iterator = this.entries();
+ while (true) {
+ var _a = iterator.next(), entry = _a.value, done = _a.done;
+ if (done) {
+ break;
+ }
+ action(entry[1], entry[0]);
}
};
return class_1;
}());
}
+ ts.shimMap = shimMap;
function length(array) {
return array ? array.length : 0;
}
@@ -751,7 +821,7 @@
}
/**
* Deduplicates an unsorted array.
- * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates.
+ * @param equalityComparer An `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`.
*/
@@ -967,6 +1037,21 @@
} };
}
ts.arrayIterator = arrayIterator;
+ function arrayReverseIterator(array) {
+ var i = array.length;
+ return {
+ next: function () {
+ if (i === 0) {
+ return { value: undefined, done: true };
+ }
+ else {
+ i--;
+ return { value: array[i], done: false };
+ }
+ }
+ };
+ }
+ ts.arrayReverseIterator = arrayReverseIterator;
/**
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
*/
@@ -1177,9 +1262,11 @@
}
for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
var arg = args_1[_a];
+ if (arg === undefined)
+ continue;
for (var p in arg) {
if (hasProperty(arg, p)) {
- t[p] = arg[p]; // TODO: GH#23368
+ t[p] = arg[p];
}
}
}
@@ -1355,6 +1442,9 @@
/** Do nothing and return true */
function returnTrue() { return true; }
ts.returnTrue = returnTrue;
+ /** Do nothing and return undefined */
+ function returnUndefined() { return undefined; }
+ ts.returnUndefined = returnUndefined;
/** Returns its argument. */
function identity(x) { return x; }
ts.identity = identity;
@@ -1501,7 +1591,7 @@
Debug.assertEachDefined = assertEachDefined;
function assertNever(member, message, stackCrawlMark) {
if (message === void 0) { message = "Illegal value:"; }
- var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member);
+ var detail = typeof member === "object" && "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member);
return fail(message + " " + detail, stackCrawlMark || assertNever);
}
Debug.assertNever = assertNever;
@@ -2804,47 +2894,53 @@
SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment";
// Enum
SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember";
+ // Unparsed
+ SyntaxKind[SyntaxKind["UnparsedPrologue"] = 279] = "UnparsedPrologue";
+ SyntaxKind[SyntaxKind["UnparsedPrepend"] = 280] = "UnparsedPrepend";
+ SyntaxKind[SyntaxKind["UnparsedText"] = 281] = "UnparsedText";
+ SyntaxKind[SyntaxKind["UnparsedInternalText"] = 282] = "UnparsedInternalText";
+ SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 283] = "UnparsedSyntheticReference";
// Top-level nodes
- SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile";
- SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle";
- SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource";
- SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles";
+ SyntaxKind[SyntaxKind["SourceFile"] = 284] = "SourceFile";
+ SyntaxKind[SyntaxKind["Bundle"] = 285] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 286] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 287] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 288] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 289] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature";
- SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag";
- SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 290] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 291] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 292] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 293] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 294] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 295] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 296] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 297] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocSignature"] = 298] = "JSDocSignature";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 299] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 300] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 301] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 302] = "JSDocCallbackTag";
+ SyntaxKind[SyntaxKind["JSDocEnumTag"] = 303] = "JSDocEnumTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 304] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 305] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocThisTag"] = 306] = "JSDocThisTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 307] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 308] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 309] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 310] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 311] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 312] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 313] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 314] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 315] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 316] = "EndOfDeclarationMarker";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 312] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 317] = "Count";
// Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment";
@@ -2871,10 +2967,10 @@
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator";
SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 288] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 310] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 299] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 310] = "LastJSDocTagNode";
/* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword";
/* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
@@ -2981,21 +3077,27 @@
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
})(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
- /* @internal */
var TokenFlags;
(function (TokenFlags) {
TokenFlags[TokenFlags["None"] = 0] = "None";
+ /* @internal */
TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
+ /* @internal */
TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
+ /* @internal */
TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
+ /* @internal */
TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
+ /* @internal */
TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
+ /* @internal */
TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
+ /* @internal */
TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
})(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
var FlowFlags;
@@ -3355,12 +3457,6 @@
TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
/* @internal */
- TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType";
- /* @internal */
- TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral";
- /* @internal */
- TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType";
- /* @internal */
TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
/* @internal */
TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
@@ -3392,28 +3488,29 @@
TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive";
TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable";
TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable";
+ /* @internal */
+ TypeFlags[TypeFlags["ObjectFlagsType"] = 3899392] = "ObjectFlagsType";
// 'Narrowable' types are types where narrowing actually narrows.
// This *should* be every type other than null, undefined, void, and never
TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable";
TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit";
/* @internal */
TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion";
+ // The following flags are aggregated during union and intersection type construction
/* @internal */
- TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening";
- /* @internal */
- TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags";
+ TypeFlags[TypeFlags["IncludesMask"] = 1835007] = "IncludesMask";
// The following flags are used for different purposes during union and intersection type construction
/* @internal */
- TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType";
+ TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
/* @internal */
- TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard";
+ TypeFlags[TypeFlags["IncludesNonWideningType"] = 2097152] = "IncludesNonWideningType";
/* @internal */
- TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject";
+ TypeFlags[TypeFlags["IncludesWildcard"] = 4194304] = "IncludesWildcard";
/* @internal */
- TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags";
+ TypeFlags[TypeFlags["IncludesEmptyObject"] = 8388608] = "IncludesEmptyObject";
// The following flag is used for different purposes by maybeTypeOfKind
/* @internal */
- TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType";
+ TypeFlags[TypeFlags["GenericMappedType"] = 131072] = "GenericMappedType";
})(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
var ObjectFlags;
(function (ObjectFlags) {
@@ -3433,7 +3530,19 @@
ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
+ /* @internal */
+ ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion";
+ /* @internal */
+ ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType";
+ /* @internal */
+ ObjectFlags[ObjectFlags["ContainsObjectLiteral"] = 262144] = "ContainsObjectLiteral";
+ /* @internal */
+ ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType";
ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
+ /* @internal */
+ ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening";
+ /* @internal */
+ ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags";
})(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
/* @internal */
var Variance;
@@ -3478,6 +3587,7 @@
InferenceFlags[InferenceFlags["None"] = 0] = "None";
InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
+ InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
})(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
/**
* Ternary values are defined such that
@@ -3585,9 +3695,10 @@
ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
- ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext";
+ ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
+ ScriptTarget[ScriptTarget["ESNext"] = 7] = "ESNext";
ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
- ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest";
+ ScriptTarget[ScriptTarget["Latest"] = 7] = "Latest";
})(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
var LanguageVariant;
(function (LanguageVariant) {
@@ -3736,6 +3847,7 @@
Extension["Js"] = ".js";
Extension["Jsx"] = ".jsx";
Extension["Json"] = ".json";
+ Extension["TsBuildInfo"] = ".tsbuildinfo";
})(Extension = ts.Extension || (ts.Extension = {}));
/* @internal */
var TransformFlags;
@@ -3743,71 +3855,69 @@
TransformFlags[TransformFlags["None"] = 0] = "None";
// Facts
// - Flags used to indicate that a node or subtree contains syntax that requires transformation.
- TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript";
- TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript";
- TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx";
- TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext";
- TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017";
- TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016";
- TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015";
+ TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
+ TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
+ TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
+ TransformFlags[TransformFlags["ContainsES2019"] = 8] = "ContainsES2019";
+ TransformFlags[TransformFlags["ContainsES2018"] = 16] = "ContainsES2018";
+ TransformFlags[TransformFlags["ContainsES2017"] = 32] = "ContainsES2017";
+ TransformFlags[TransformFlags["ContainsES2016"] = 64] = "ContainsES2016";
TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015";
- TransformFlags[TransformFlags["Generator"] = 256] = "Generator";
- TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
- TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment";
- TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment";
+ TransformFlags[TransformFlags["ContainsGenerator"] = 256] = "ContainsGenerator";
+ TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 512] = "ContainsDestructuringAssignment";
// Markers
// - Flags used to indicate that a subtree contains a specific transformation.
- TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax";
- TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis";
- TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis";
- TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName";
- TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments";
- TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread";
- TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread";
- TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName";
- TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding";
- TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern";
- TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield";
- TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion";
- TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport";
- TransformFlags[TransformFlags["Super"] = 33554432] = "Super";
- TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper";
+ TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 1024] = "ContainsTypeScriptClassSyntax";
+ TransformFlags[TransformFlags["ContainsLexicalThis"] = 2048] = "ContainsLexicalThis";
+ TransformFlags[TransformFlags["ContainsRestOrSpread"] = 4096] = "ContainsRestOrSpread";
+ TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 8192] = "ContainsObjectRestOrSpread";
+ TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 16384] = "ContainsComputedPropertyName";
+ TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 32768] = "ContainsBlockScopedBinding";
+ TransformFlags[TransformFlags["ContainsBindingPattern"] = 65536] = "ContainsBindingPattern";
+ TransformFlags[TransformFlags["ContainsYield"] = 131072] = "ContainsYield";
+ TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 262144] = "ContainsHoistedDeclarationOrCompletion";
+ TransformFlags[TransformFlags["ContainsDynamicImport"] = 524288] = "ContainsDynamicImport";
// Please leave this as 1 << 29.
// It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
// It is a good reminder of how much room we have left
TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
// Assertions
// - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
- TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript";
- TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx";
- TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext";
- TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017";
- TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016";
- TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015";
- TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator";
- TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment";
+ TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
+ TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
+ TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
+ TransformFlags[TransformFlags["AssertES2019"] = 8] = "AssertES2019";
+ TransformFlags[TransformFlags["AssertES2018"] = 16] = "AssertES2018";
+ TransformFlags[TransformFlags["AssertES2017"] = 32] = "AssertES2017";
+ TransformFlags[TransformFlags["AssertES2016"] = 64] = "AssertES2016";
+ TransformFlags[TransformFlags["AssertES2015"] = 128] = "AssertES2015";
+ TransformFlags[TransformFlags["AssertGenerator"] = 256] = "AssertGenerator";
+ TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 512] = "AssertDestructuringAssignment";
// Scope Exclusions
// - Bitmasks that exclude flags from propagating out of a specific context
// into the subtree flags of their container.
- TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes";
- TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes";
- TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes";
- TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes";
- TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes";
- TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes";
- TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes";
- TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes";
- TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes";
- TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes";
- TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes";
- TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes";
- TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes";
- TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes";
- TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes";
- TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes";
+ TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
+ TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
+ TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
+ TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 537371648] = "ArrowFunctionExcludes";
+ TransformFlags[TransformFlags["FunctionExcludes"] = 537373696] = "FunctionExcludes";
+ TransformFlags[TransformFlags["ConstructorExcludes"] = 537372672] = "ConstructorExcludes";
+ TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 537372672] = "MethodOrAccessorExcludes";
+ TransformFlags[TransformFlags["PropertyExcludes"] = 536872960] = "PropertyExcludes";
+ TransformFlags[TransformFlags["ClassExcludes"] = 536888320] = "ClassExcludes";
+ TransformFlags[TransformFlags["ModuleExcludes"] = 537168896] = "ModuleExcludes";
+ TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
+ TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536896512] = "ObjectLiteralExcludes";
+ TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536875008] = "ArrayLiteralOrCallOrNewExcludes";
+ TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 536944640] = "VariableDeclarationListExcludes";
+ TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
+ TransformFlags[TransformFlags["CatchClauseExcludes"] = 536879104] = "CatchClauseExcludes";
+ TransformFlags[TransformFlags["BindingPatternExcludes"] = 536875008] = "BindingPatternExcludes";
+ // Propagating flags
+ // - Bitmasks for flags that should propagate from a child
+ TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 2048] = "PropertyNamePropagatingFlags";
// Masks
// - Additional bitmasks
- TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask";
})(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
var EmitFlags;
(function (EmitFlags) {
@@ -3889,6 +3999,20 @@
EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
})(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
+ /*@internal*/
+ var BundleFileSectionKind;
+ (function (BundleFileSectionKind) {
+ BundleFileSectionKind["Prologue"] = "prologue";
+ BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
+ BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
+ BundleFileSectionKind["Reference"] = "reference";
+ BundleFileSectionKind["Type"] = "type";
+ BundleFileSectionKind["Lib"] = "lib";
+ BundleFileSectionKind["Prepend"] = "prepend";
+ BundleFileSectionKind["Text"] = "text";
+ BundleFileSectionKind["Internal"] = "internal";
+ // comments?
+ })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
var ListFormat;
(function (ListFormat) {
ListFormat[ListFormat["None"] = 0] = "None";
@@ -4035,8 +4159,11 @@
*/
/* @internal */
function generateDjb2Hash(data) {
- var chars = data.split("").map(function (str) { return str.charCodeAt(0); });
- return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381);
+ var acc = 5381;
+ for (var i = 0; i < data.length; i++) {
+ acc = ((acc << 5) + acc) + data.charCodeAt(i);
+ }
+ return acc.toString();
}
ts.generateDjb2Hash = generateDjb2Hash;
/**
@@ -4296,6 +4423,8 @@
: FileWatcherEventKind.Changed;
}
ts.getFileWatcherEventKind = getFileWatcherEventKind;
+ /*@internal*/
+ ts.ignoredPaths = ["/node_modules/.", "/.git"];
/**
* 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
@@ -4320,6 +4449,8 @@
else {
directoryWatcher = {
watcher: host.watchDirectory(dirName, function (fileName) {
+ if (isIgnoredPath(fileName))
+ return;
// Call the actual callback
callbackCache.forEach(function (callbacks, rootDirName) {
if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
@@ -4369,7 +4500,7 @@
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 filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
+ return !isIgnoredPath(childFullName) && 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;
/**
@@ -4386,6 +4517,16 @@
(newChildWatches || (newChildWatches = [])).push(childWatcher);
}
}
+ function isIgnoredPath(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
+ }
+ function isInPath(path, searchPath) {
+ if (ts.stringContains(path, searchPath))
+ return true;
+ if (host.useCaseSensitiveFileNames)
+ return false;
+ return ts.stringContains(toCanonicalFilePath(path), searchPath);
+ }
}
ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher;
function getNodeMajorVersion() {
@@ -4454,8 +4595,18 @@
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!nodeSystem.directoryExists(directoryName)) {
+ // Wrapped in a try-catch to prevent crashing if we are in a race
+ // with another copy of ourselves to create the same directory
+ try {
_fs.mkdirSync(directoryName);
}
+ catch (e) {
+ if (e.code !== "EEXIST") {
+ // Failed for some other reason (access denied?); still throw
+ throw e;
+ }
+ }
+ }
},
getExecutingFilePath: function () {
return __filename;
@@ -4471,7 +4622,7 @@
getModifiedTime: getModifiedTime,
setModifiedTime: setModifiedTime,
deleteFile: deleteFile,
- createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash,
+ createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
createSHA256Hash: _crypto ? createSHA256Hash : undefined,
getMemoryUsage: function () {
if (global.gc) {
@@ -4859,7 +5010,7 @@
}
}
function readDirectory(path, extensions, excludes, includes, depth) {
- return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries);
+ return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
}
function fileSystemEntryExists(path, entryKind) {
try {
@@ -4915,11 +5066,6 @@
return;
}
}
- function createMD5HashUsingNativeCrypto(data) {
- var hash = _crypto.createHash("md5");
- hash.update(data);
- return hash.digest("hex");
- }
function createSHA256Hash(data) {
var hash = _crypto.createHash("sha256");
hash.update(data);
@@ -5180,7 +5326,6 @@
Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."),
Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."),
- Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."),
Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."),
A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."),
Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."),
@@ -5271,6 +5416,8 @@
An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."),
A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."),
A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."),
+ readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types: diag(1354, ts.DiagnosticCategory.Error, "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354", "'readonly' type modifier is only permitted on array and tuple literal types."),
+ A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal: diag(1355, ts.DiagnosticCategory.Error, "A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal_1355", "A 'const' assertion can only be applied to a string, number, boolean, array, or object literal."),
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."),
@@ -5365,7 +5512,7 @@
Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."),
Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
- Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."),
+ This_overload_signature_is_not_compatible_with_its_implementation_signature: diag(2394, ts.DiagnosticCategory.Error, "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394", "This overload signature is not compatible with its implementation signature."),
Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."),
Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."),
Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."),
@@ -5538,15 +5685,20 @@
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."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."),
Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."),
_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
+ Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."),
+ Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
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."),
@@ -5653,6 +5805,12 @@
This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."),
This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."),
_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."),
+ Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided: diag(2748, ts.DiagnosticCategory.Error, "Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided_2748", "Cannot access ambient const enums when the '--isolatedModules' flag is provided."),
+ _0_refers_to_a_value_but_is_being_used_as_a_type_here: diag(2749, ts.DiagnosticCategory.Error, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_2749", "'{0}' refers to a value, but is being used as a type here."),
+ The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
+ Circularity_originates_in_type_at_this_location: diag(2751, ts.DiagnosticCategory.Error, "Circularity_originates_in_type_at_this_location_2751", "Circularity originates in type at this location."),
+ The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
+ Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
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}'."),
@@ -5736,6 +5894,7 @@
Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
@@ -5784,7 +5943,7 @@
Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."),
Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
- Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."),
+ Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'."),
Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."),
Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
@@ -6003,6 +6162,16 @@
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."),
Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
+ Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
+ Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
+ A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
+ A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
+ Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
+ Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
+ Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
+ Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
+ Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
+ Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
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."),
The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
@@ -6039,7 +6208,7 @@
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'."),
+ The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."),
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."),
Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
@@ -6219,6 +6388,7 @@
Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
+ Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
};
})(ts || (ts = {}));
var ts;
@@ -6706,16 +6876,20 @@
return pos;
}
var shebangTriviaRegex = /^#!.*/;
+ /*@internal*/
function isShebangTrivia(text, pos) {
// Shebangs check must only be done at the start of the file
ts.Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
+ ts.isShebangTrivia = isShebangTrivia;
+ /*@internal*/
function scanShebangTrivia(text, pos) {
var shebang = shebangTriviaRegex.exec(text)[0];
pos = pos + shebang.length;
return pos;
}
+ ts.scanShebangTrivia = scanShebangTrivia;
/**
* Invokes a callback for each comment range following the provided position.
*
@@ -6742,8 +6916,15 @@
var pendingKind;
var pendingHasTrailingNewLine;
var hasPendingCommentRange = false;
- var collecting = trailing || pos === 0;
+ var collecting = trailing;
var accumulator = initial;
+ if (pos === 0) {
+ collecting = true;
+ var shebang = getShebang(text);
+ if (shebang) {
+ pos = shebang.length;
+ }
+ }
scan: while (pos >= 0 && pos < text.length) {
var ch = text.charCodeAt(pos);
switch (ch) {
@@ -7978,6 +8159,7 @@
}
pos++;
}
+ tokenValue = text.substring(startPos, pos);
return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
}
// Scans a JSX identifier; these differ from normal identifiers in that
@@ -8059,8 +8241,8 @@
pos++;
return token = 14 /* NoSubstitutionTemplateLiteral */;
}
- if (isIdentifierStart(ch, 6 /* Latest */)) {
- while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) {
+ if (isIdentifierStart(ch, 7 /* Latest */)) {
+ while (isIdentifierPart(text.charCodeAt(pos), 7 /* Latest */) && pos < end) {
pos++;
}
tokenValue = text.substring(tokenPos, pos);
@@ -8418,7 +8600,7 @@
}
}
function getSourceFileOfNode(node) {
- while (node && node.kind !== 279 /* SourceFile */) {
+ while (node && node.kind !== 284 /* SourceFile */) {
node = node.parent;
}
return node;
@@ -8505,10 +8687,7 @@
return !nodeIsMissing(node);
}
ts.nodeIsPresent = nodeIsPresent;
- /**
- * Prepends statements to an array while taking care of prologue directives.
- */
- function addStatementsAfterPrologue(to, from) {
+ function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
if (from === undefined || from.length === 0)
return to;
var statementIndex = 0;
@@ -8521,7 +8700,44 @@
to.splice.apply(to, [statementIndex, 0].concat(from));
return to;
}
- ts.addStatementsAfterPrologue = addStatementsAfterPrologue;
+ function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
+ if (statement === undefined)
+ return to;
+ 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(statementIndex, 0, statement);
+ return to;
+ }
+ function isAnyPrologueDirective(node) {
+ return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
+ }
+ /**
+ * Prepends statements to an array while taking care of prologue directives.
+ */
+ function insertStatementsAfterStandardPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isPrologueDirective);
+ }
+ ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
+ function insertStatementsAfterCustomPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
+ }
+ ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
+ /**
+ * Prepends statements to an array while taking care of prologue directives.
+ */
+ function insertStatementAfterStandardPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isPrologueDirective);
+ }
+ ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
+ function insertStatementAfterCustomPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
+ }
+ ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
/**
* Determine if the given comment is a triple-slash
*
@@ -8564,7 +8780,7 @@
// 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 === 306 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 311 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -8583,7 +8799,7 @@
}
ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
function isJSDocTypeExpressionOrChild(node) {
- return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
+ return node.kind === 288 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
}
function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
@@ -8710,7 +8926,7 @@
return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body);
}
function isBlockScopedContainerTopLevel(node) {
- return node.kind === 279 /* SourceFile */ ||
+ return node.kind === 284 /* SourceFile */ ||
node.kind === 244 /* ModuleDeclaration */ ||
ts.isFunctionLike(node);
}
@@ -8728,7 +8944,7 @@
// - 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 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node.parent);
case 245 /* ModuleBlock */:
return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
@@ -8746,7 +8962,7 @@
ts.isEffectiveExternalModule = isEffectiveExternalModule;
function isBlockScope(node, parentNode) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 274 /* CatchClause */:
case 244 /* ModuleDeclaration */:
@@ -8771,9 +8987,9 @@
ts.isBlockScope = isBlockScope;
function isDeclarationWithTypeParameters(node) {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
- case 293 /* JSDocSignature */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 298 /* JSDocSignature */:
return true;
default:
ts.assertType(node);
@@ -8789,12 +9005,12 @@
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
@@ -8939,7 +9155,7 @@
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* 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
@@ -9114,7 +9330,7 @@
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case 150 /* TypeParameter */:
return node === parent.constraint;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return node === parent.constraint;
case 154 /* PropertyDeclaration */:
case 153 /* PropertySignature */:
@@ -9374,7 +9590,7 @@
}
ts.getContainingClass = getContainingClass;
function getThisContainer(node, includeArrowFunctions) {
- ts.Debug.assert(node.kind !== 279 /* SourceFile */);
+ ts.Debug.assert(node.kind !== 284 /* SourceFile */);
while (true) {
node = node.parent;
if (!node) {
@@ -9428,7 +9644,7 @@
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 243 /* EnumDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return node;
}
}
@@ -9511,6 +9727,11 @@
}
}
ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
+ function isSuperOrSuperProperty(node) {
+ return node.kind === 98 /* SuperKeyword */
+ || isSuperProperty(node);
+ }
+ ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
/**
* Determines whether a node is a property or element access expression for `super`.
*/
@@ -10136,7 +10357,7 @@
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
function isJSDocTypeAlias(node) {
- return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 309 /* JSDocTypedefTag */ || node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocTypeAlias = isJSDocTypeAlias;
function isTypeAlias(node) {
@@ -10280,7 +10501,7 @@
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 === 290 /* JSDocVariadicType */;
+ return node.dotDotDotToken !== undefined || !!type && type.kind === 295 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -10518,14 +10739,15 @@
}
ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
function getEffectiveBaseTypeNode(node) {
- if (isInJSFile(node)) {
+ var baseType = getClassExtendsHeritageElement(node);
+ if (baseType && isInJSFile(node)) {
// Prefer an @augments tag because it may have type parameters.
var tag = ts.getJSDocAugmentsTag(node);
if (tag) {
return tag.class;
}
}
- return getClassExtendsHeritageElement(node);
+ return baseType;
}
ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
function getClassExtendsHeritageElement(node) {
@@ -10764,7 +10986,7 @@
|| kind === 158 /* GetAccessor */
|| kind === 159 /* SetAccessor */
|| kind === 244 /* ModuleDeclaration */
- || kind === 279 /* SourceFile */;
+ || kind === 284 /* SourceFile */;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(range) {
@@ -10841,7 +11063,7 @@
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return 0;
case 208 /* SpreadElement */:
return 1;
@@ -11159,6 +11381,9 @@
lineStart = true;
}
}
+ function getTextPosWithWriteLine() {
+ return lineStart ? output.length : (output.length + newLine.length);
+ }
reset();
return {
write: write,
@@ -11187,7 +11412,8 @@
writeStringLiteral: write,
writeSymbol: function (s, _) { return write(s); },
writeTrailingSemicolon: write,
- writeComment: write
+ writeComment: write,
+ getTextPosWithWriteLine: getTextPosWithWriteLine
};
}
ts.createTextWriter = createTextWriter;
@@ -11316,23 +11542,27 @@
function getSourceFilesToEmit(host, targetSourceFile) {
var options = host.getCompilerOptions();
var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); };
+ var getResolvedProjectReferenceToRedirect = function (fileName) { return host.getResolvedProjectReferenceToRedirect(fileName); };
if (options.outFile || options.out) {
var moduleKind = ts.getEmitModuleKind(options);
var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
// Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
return ts.filter(host.getSourceFiles(), function (sourceFile) {
- return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary);
+ return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect);
});
}
else {
var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
- return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); });
+ return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
}
}
ts.getSourceFilesToEmit = getSourceFilesToEmit;
/** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
- function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) {
- return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile);
+ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect) {
+ return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
+ !sourceFile.isDeclarationFile &&
+ !isSourceFileFromExternalLibrary(sourceFile) &&
+ !(isJsonSourceFile(sourceFile) && getResolvedProjectReferenceToRedirect(sourceFile.fileName));
}
ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
function getSourceFilePathInNewDir(fileName, host, newDirPath) {
@@ -11478,7 +11708,7 @@
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 === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 296 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
}
/**
* Gets the effective type annotation of the value parameter of a set accessor. If the node
@@ -12383,7 +12613,7 @@
}
ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
function getObjectFlags(type) {
- return type.flags & 524288 /* Object */ ? type.objectFlags : 0;
+ return type.flags & 3899392 /* ObjectFlagsType */ ? type.objectFlags : 0;
}
ts.getObjectFlags = getObjectFlags;
function typeHasCallOrConstructSignatures(type, checker) {
@@ -12450,25 +12680,37 @@
|| kind === 96 /* NullKeyword */
|| kind === 132 /* NeverKeyword */
|| kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
+ || kind === 289 /* JSDocAllType */
+ || kind === 290 /* JSDocUnknownType */
+ || kind === 291 /* JSDocNullableType */
+ || kind === 292 /* JSDocNonNullableType */
+ || kind === 293 /* JSDocOptionalType */
+ || kind === 294 /* JSDocFunctionType */
+ || kind === 295 /* JSDocVariadicType */;
}
ts.isTypeNodeKind = isTypeNodeKind;
function isAccessExpression(node) {
return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */;
}
ts.isAccessExpression = isAccessExpression;
+ function isBundleFileTextLike(section) {
+ switch (section.kind) {
+ case "text" /* Text */:
+ case "internal" /* Internal */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isBundleFileTextLike = isBundleFileTextLike;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
switch (options.target) {
- case 6 /* ESNext */:
+ case 7 /* ESNext */:
return "lib.esnext.full.d.ts";
+ case 6 /* ES2019 */:
+ return "lib.es2019.full.d.ts";
case 5 /* ES2018 */:
return "lib.es2018.full.d.ts";
case 4 /* ES2017 */:
@@ -12922,8 +13164,8 @@
switch (declaration.kind) {
case 72 /* Identifier */:
return declaration;
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */: {
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */: {
var name = declaration.name;
if (name.kind === 148 /* QualifiedName */) {
return name.right;
@@ -12947,7 +13189,7 @@
return undefined;
}
}
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
case 254 /* ExportAssignment */: {
var expression = declaration.expression;
@@ -13151,7 +13393,7 @@
return ts.emptyArray;
}
if (ts.isJSDocTypeAlias(node)) {
- ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */);
+ ts.Debug.assert(node.parent.kind === 296 /* JSDocComment */);
return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
}
if (node.typeParameters) {
@@ -13413,12 +13655,17 @@
return node.kind === 194 /* TypeAssertionExpression */;
}
ts.isTypeAssertion = isTypeAssertion;
+ function isConstTypeReference(node) {
+ return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
+ node.typeName.escapedText === "const" && !node.typeArguments;
+ }
+ ts.isConstTypeReference = isConstTypeReference;
function isParenthesizedExpression(node) {
return node.kind === 195 /* ParenthesizedExpression */;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 308 /* PartiallyEmittedExpression */) {
+ while (node.kind === 313 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13765,108 +14012,128 @@
ts.isEnumMember = isEnumMember;
// Top-level nodes
function isSourceFile(node) {
- return node.kind === 279 /* SourceFile */;
+ return node.kind === 284 /* SourceFile */;
}
ts.isSourceFile = isSourceFile;
function isBundle(node) {
- return node.kind === 280 /* Bundle */;
+ return node.kind === 285 /* Bundle */;
}
ts.isBundle = isBundle;
function isUnparsedSource(node) {
- return node.kind === 281 /* UnparsedSource */;
+ return node.kind === 286 /* UnparsedSource */;
}
ts.isUnparsedSource = isUnparsedSource;
+ function isUnparsedPrepend(node) {
+ return node.kind === 280 /* UnparsedPrepend */;
+ }
+ ts.isUnparsedPrepend = isUnparsedPrepend;
+ function isUnparsedTextLike(node) {
+ switch (node.kind) {
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isUnparsedTextLike = isUnparsedTextLike;
+ function isUnparsedNode(node) {
+ return isUnparsedTextLike(node) ||
+ node.kind === 279 /* UnparsedPrologue */ ||
+ node.kind === 283 /* UnparsedSyntheticReference */;
+ }
+ ts.isUnparsedNode = isUnparsedNode;
// JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 283 /* JSDocTypeExpression */;
+ return node.kind === 288 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 284 /* JSDocAllType */;
+ return node.kind === 289 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 285 /* JSDocUnknownType */;
+ return node.kind === 290 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 286 /* JSDocNullableType */;
+ return node.kind === 291 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 287 /* JSDocNonNullableType */;
+ return node.kind === 292 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 288 /* JSDocOptionalType */;
+ return node.kind === 293 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 289 /* JSDocFunctionType */;
+ return node.kind === 294 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 290 /* JSDocVariadicType */;
+ return node.kind === 295 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 291 /* JSDocComment */;
+ return node.kind === 296 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 295 /* JSDocAugmentsTag */;
+ return node.kind === 300 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 296 /* JSDocClassTag */;
+ return node.kind === 301 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocEnumTag(node) {
- return node.kind === 298 /* JSDocEnumTag */;
+ return node.kind === 303 /* JSDocEnumTag */;
}
ts.isJSDocEnumTag = isJSDocEnumTag;
function isJSDocThisTag(node) {
- return node.kind === 301 /* JSDocThisTag */;
+ return node.kind === 306 /* JSDocThisTag */;
}
ts.isJSDocThisTag = isJSDocThisTag;
function isJSDocParameterTag(node) {
- return node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 300 /* JSDocReturnTag */;
+ return node.kind === 305 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 302 /* JSDocTypeTag */;
+ return node.kind === 307 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 303 /* JSDocTemplateTag */;
+ return node.kind === 308 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 304 /* JSDocTypedefTag */;
+ return node.kind === 309 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */;
+ return node.kind === 310 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 310 /* JSDocPropertyTag */ || node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 292 /* JSDocTypeLiteral */;
+ return node.kind === 297 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
function isJSDocCallbackTag(node) {
- return node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocCallbackTag = isJSDocCallbackTag;
function isJSDocSignature(node) {
- return node.kind === 293 /* JSDocSignature */;
+ return node.kind === 298 /* JSDocSignature */;
}
ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
@@ -13877,7 +14144,7 @@
(function (ts) {
/* @internal */
function isSyntaxList(n) {
- return n.kind === 306 /* SyntaxList */;
+ return n.kind === 311 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
/* @internal */
@@ -14029,11 +14296,11 @@
switch (kind) {
case 155 /* MethodSignature */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 166 /* ConstructorType */:
return true;
default:
@@ -14324,8 +14591,8 @@
case 208 /* SpreadElement */:
case 212 /* AsExpression */:
case 210 /* OmittedExpression */:
- case 309 /* CommaListExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 314 /* CommaListExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -14339,12 +14606,12 @@
ts.isAssertionExpression = isAssertionExpression;
/* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 308 /* PartiallyEmittedExpression */;
+ return node.kind === 313 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
/* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 307 /* NotEmittedStatement */;
+ return node.kind === 312 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
@@ -14455,9 +14722,9 @@
|| kind === 242 /* TypeAliasDeclaration */
|| kind === 150 /* TypeParameter */
|| kind === 237 /* VariableDeclaration */
- || kind === 304 /* JSDocTypedefTag */
- || kind === 297 /* JSDocCallbackTag */
- || kind === 305 /* JSDocPropertyTag */;
+ || kind === 309 /* JSDocTypedefTag */
+ || kind === 302 /* JSDocCallbackTag */
+ || kind === 310 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
return kind === 239 /* FunctionDeclaration */
@@ -14492,14 +14759,14 @@
|| kind === 219 /* VariableStatement */
|| kind === 224 /* WhileStatement */
|| kind === 231 /* WithStatement */
- || kind === 307 /* NotEmittedStatement */
- || kind === 311 /* EndOfDeclarationMarker */
- || kind === 310 /* MergeDeclarationMarker */;
+ || kind === 312 /* NotEmittedStatement */
+ || kind === 316 /* EndOfDeclarationMarker */
+ || kind === 315 /* MergeDeclarationMarker */;
}
/* @internal */
function isDeclaration(node) {
if (node.kind === 150 /* TypeParameter */) {
- return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node);
+ return (node.parent && node.parent.kind !== 308 /* JSDocTemplateTag */) || ts.isInJSFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -14594,18 +14861,18 @@
/** True if node is of some JSDoc syntax kind. */
/* @internal */
function isJSDocNode(node) {
- return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */;
+ return node.kind >= 288 /* FirstJSDocNode */ && node.kind <= 310 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
+ return node.kind === 296 /* 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 >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */;
+ return node.kind >= 299 /* FirstJSDocTagNode */ && node.kind <= 310 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -14922,6 +15189,10 @@
return !!(compilerOptions.declaration || compilerOptions.composite);
}
ts.getEmitDeclarations = getEmitDeclarations;
+ function isIncrementalCompilation(options) {
+ return !!(options.incremental || options.composite);
+ }
+ ts.isIncrementalCompilation = isIncrementalCompilation;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
}
@@ -15609,7 +15880,7 @@
}
ts.getRegexFromPattern = getRegexFromPattern;
/** @param path directory of the tsconfig.json */
- function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) {
+ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
path = ts.normalizePath(path);
currentDirectory = ts.normalizePath(currentDirectory);
var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
@@ -15619,12 +15890,18 @@
// Associate an array of results with each include regex. This keeps results in order of the "include" order.
// If there are no "includes", then just put everything in results[0].
var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
+ var visited = ts.createMap();
+ var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
var basePath = _a[_i];
visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
}
return ts.flatten(results);
function visitDirectory(path, absolutePath, depth) {
+ var canonicalPath = toCanonical(realpath(absolutePath));
+ if (visited.has(canonicalPath))
+ return;
+ visited.set(canonicalPath, true);
var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
var _loop_1 = function (current) {
var name = combinePaths(path, current);
@@ -16007,6 +16284,19 @@
return arr.slice(index);
}
ts.sliceAfter = sliceAfter;
+ function addRelatedInfo(diagnostic) {
+ var _a;
+ var relatedInformation = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ relatedInformation[_i - 1] = arguments[_i];
+ }
+ if (!diagnostic.relatedInformation) {
+ diagnostic.relatedInformation = [];
+ }
+ (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
+ return diagnostic;
+ }
+ ts.addRelatedInfo = addRelatedInfo;
function minAndMax(arr, getValue) {
Debug.assert(arr.length !== 0);
var min = getValue(arr[0]);
@@ -16206,7 +16496,7 @@
var SourceFileConstructor;
// tslint:enable variable-name
function createNode(kind, pos, end) {
- if (kind === 279 /* SourceFile */) {
+ if (kind === 284 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 72 /* Identifier */) {
@@ -16457,7 +16747,7 @@
case 218 /* Block */:
case 245 /* ModuleBlock */:
return visitNodes(cbNode, cbNodes, node.statements);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return visitNodes(cbNode, cbNodes, node.statements) ||
visitNode(cbNode, node.endOfFileToken);
case 219 /* VariableStatement */:
@@ -16606,7 +16896,7 @@
return visitNode(cbNode, node.expression);
case 258 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
case 260 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
@@ -16635,60 +16925,60 @@
return visitNode(cbNode, node.tagName);
case 171 /* OptionalType */:
case 172 /* RestType */:
- case 283 /* JSDocTypeExpression */:
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 288 /* JSDocOptionalType */:
- case 290 /* JSDocVariadicType */:
+ case 288 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 293 /* JSDocOptionalType */:
+ case 295 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return visitNode(cbNode, node.tagName) ||
(node.isNameFirst
? visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression)
: visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name));
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.constraint) ||
visitNodes(cbNode, cbNodes, node.typeParameters);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return visitNode(cbNode, node.tagName) ||
(node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ node.typeExpression.kind === 288 /* JSDocTypeExpression */
? visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName)
: visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression));
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.typeExpression);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return ts.forEach(node.jsDocPropertyTags, cbNode);
- case 294 /* JSDocTag */:
- case 296 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
return visitNode(cbNode, node.tagName);
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -16768,7 +17058,7 @@
(function (Parser) {
// Share a single scanner across all calls to parse a source file. This helps speed things
// up by avoiding the cost of creating/compiling scanners over and over again.
- var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true);
+ var scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ true);
var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */;
// capture constructors in 'initializeState' to avoid null checks
// tslint:disable variable-name
@@ -17062,7 +17352,7 @@
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(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
+ var sourceFile = new SourceFileConstructor(284 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
@@ -18262,9 +18552,9 @@
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(284 /* JSDocAllType */);
+ var result = createNode(289 /* JSDocAllType */);
if (postFixEquals) {
- return createPostfixType(288 /* JSDocOptionalType */, result);
+ return createPostfixType(293 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -18272,7 +18562,7 @@
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(287 /* JSDocNonNullableType */);
+ var result = createNode(292 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -18296,18 +18586,18 @@
token() === 30 /* GreaterThanToken */ ||
token() === 59 /* EqualsToken */ ||
token() === 50 /* BarToken */) {
- var result = createNode(285 /* JSDocUnknownType */, pos);
+ var result = createNode(290 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(286 /* JSDocNullableType */, pos);
+ var result = createNode(291 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(289 /* JSDocFunctionType */);
+ var result = createNodeWithJSDoc(294 /* JSDocFunctionType */);
nextToken();
fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
@@ -18331,12 +18621,12 @@
var type = parseTypeOrTypePredicate();
scanner.setInJSDocType(false);
if (dotdotdot) {
- var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos);
+ var variadic = createNode(295 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 59 /* EqualsToken */) {
- return createPostfixType(288 /* JSDocOptionalType */, type);
+ return createPostfixType(293 /* JSDocOptionalType */, type);
}
return type;
}
@@ -18708,7 +18998,7 @@
return finishNode(node);
}
var type = parseType();
- if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) {
+ if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 291 /* JSDocNullableType */ && type.pos === type.type.pos) {
type.kind = 171 /* OptionalType */;
}
return type;
@@ -18846,6 +19136,7 @@
case 135 /* NumberKeyword */:
case 146 /* BigIntKeyword */:
case 123 /* BooleanKeyword */:
+ case 133 /* ReadonlyKeyword */:
case 139 /* SymbolKeyword */:
case 142 /* UniqueKeyword */:
case 106 /* VoidKeyword */:
@@ -18894,14 +19185,14 @@
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 52 /* ExclamationToken */:
- type = createPostfixType(287 /* JSDocNonNullableType */, type);
+ type = createPostfixType(292 /* JSDocNonNullableType */, type);
break;
case 56 /* 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 = createPostfixType(286 /* JSDocNullableType */, type);
+ type = createPostfixType(291 /* JSDocNullableType */, type);
break;
case 22 /* OpenBracketToken */:
parseExpected(22 /* OpenBracketToken */);
@@ -18951,6 +19242,7 @@
switch (operator) {
case 129 /* KeyOfKeyword */:
case 142 /* UniqueKeyword */:
+ case 133 /* ReadonlyKeyword */:
return parseTypeOperator(operator);
case 127 /* InferKeyword */:
return parseInferType();
@@ -20010,7 +20302,8 @@
}
function parseJsxText() {
var node = createNode(11 /* JsxText */);
- node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
+ node.text = scanner.getTokenValue();
+ node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
currentToken = scanner.scanJsxToken();
return finishNode(node);
}
@@ -21825,8 +22118,8 @@
var JSDocParser;
(function (JSDocParser) {
function parseJSDocTypeExpressionForTests(content, start, length) {
- initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
- sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
+ initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ sourceFile = createSourceFile("file.js", 7 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
scanner.setText(content, start, length);
currentToken = scanner.scan();
var jsDocTypeExpression = parseJSDocTypeExpression();
@@ -21837,7 +22130,7 @@
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
// Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(283 /* JSDocTypeExpression */);
+ var result = createNode(288 /* JSDocTypeExpression */);
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -21848,7 +22141,7 @@
}
JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
function parseIsolatedJSDocComment(content, start, length) {
- initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion
var jsDoc = parseJSDocCommentWorker(start, length);
var diagnostics = parseDiagnostics;
@@ -22000,7 +22293,7 @@
}
}
function createJSDocComment() {
- var result = createNode(291 /* JSDocComment */, start);
+ var result = createNode(296 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -22167,7 +22460,7 @@
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(start, tagName) {
- var result = createNode(294 /* JSDocTag */, start);
+ var result = createNode(299 /* JSDocTag */, start);
result.tagName = tagName;
return finishNode(result);
}
@@ -22226,8 +22519,8 @@
typeExpression = tryParseTypeExpression();
}
var result = target === 1 /* Property */ ?
- createNode(305 /* JSDocPropertyTag */, start) :
- createNode(299 /* JSDocParameterTag */, start);
+ createNode(310 /* JSDocPropertyTag */, start) :
+ createNode(304 /* JSDocParameterTag */, start);
var comment = parseTagComments(indent + scanner.getStartPos() - start);
var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
if (nestedTypeLiteral) {
@@ -22244,18 +22537,18 @@
}
function parseNestedTypeLiteral(typeExpression, name, target, indent) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(288 /* 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, indent, name); })) {
- if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) {
+ if (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 169 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
@@ -22266,25 +22559,25 @@
}
}
function parseReturnTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 305 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(300 /* JSDocReturnTag */, start);
+ var result = createNode(305 /* JSDocReturnTag */, start);
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 307 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(302 /* JSDocTypeTag */, start);
+ var result = createNode(307 /* JSDocTypeTag */, start);
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(start, tagName) {
- var result = createNode(295 /* JSDocAugmentsTag */, start);
+ var result = createNode(300 /* JSDocAugmentsTag */, start);
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
return finishNode(result);
@@ -22311,19 +22604,19 @@
return node;
}
function parseClassTag(start, tagName) {
- var tag = createNode(296 /* JSDocClassTag */, start);
+ var tag = createNode(301 /* JSDocClassTag */, start);
tag.tagName = tagName;
return finishNode(tag);
}
function parseThisTag(start, tagName) {
- var tag = createNode(301 /* JSDocThisTag */, start);
+ var tag = createNode(306 /* JSDocThisTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
return finishNode(tag);
}
function parseEnumTag(start, tagName) {
- var tag = createNode(298 /* JSDocEnumTag */, start);
+ var tag = createNode(303 /* JSDocEnumTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
@@ -22332,7 +22625,7 @@
function parseTypedefTag(start, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespaceOrAsterisk();
- var typedefTag = createNode(304 /* JSDocTypedefTag */, start);
+ var typedefTag = createNode(309 /* JSDocTypedefTag */, start);
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace();
typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
@@ -22346,9 +22639,9 @@
var childTypeTag = void 0;
while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start);
}
- if (child.kind === 302 /* JSDocTypeTag */) {
+ if (child.kind === 307 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -22394,14 +22687,14 @@
return typeNameOrNamespaceName;
}
function parseCallbackTag(start, tagName, indent) {
- var callbackTag = createNode(297 /* JSDocCallbackTag */, start);
+ var callbackTag = createNode(302 /* JSDocCallbackTag */, start);
callbackTag.tagName = tagName;
callbackTag.fullName = parseJSDocTypeNameWithNamespace();
callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
skipWhitespace();
callbackTag.comment = parseTagComments(indent);
var child;
- var jsdocSignature = createNode(293 /* JSDocSignature */, start);
+ var jsdocSignature = createNode(298 /* JSDocSignature */, start);
jsdocSignature.parameters = [];
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
@@ -22409,7 +22702,7 @@
var returnTag = tryParse(function () {
if (parseOptionalJsdoc(58 /* AtToken */)) {
var tag = parseTag(indent);
- if (tag && tag.kind === 300 /* JSDocReturnTag */) {
+ if (tag && tag.kind === 305 /* JSDocReturnTag */) {
return tag;
}
}
@@ -22454,7 +22747,7 @@
case 58 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target, indent);
- if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) &&
+ if (child && (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) &&
target !== 4 /* CallbackParameter */ &&
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
@@ -22524,7 +22817,7 @@
skipWhitespace();
typeParameters.push(typeParameter);
} while (parseOptionalJsdoc(27 /* CommaToken */));
- var result = createNode(303 /* JSDocTemplateTag */, start);
+ var result = createNode(308 /* JSDocTemplateTag */, start);
result.tagName = tagName;
result.constraint = constraint;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -23302,6 +23595,7 @@
["es2016", "lib.es2016.d.ts"],
["es2017", "lib.es2017.d.ts"],
["es2018", "lib.es2018.d.ts"],
+ ["es2019", "lib.es2019.d.ts"],
["esnext", "lib.esnext.d.ts"],
// Host only
["dom", "lib.dom.d.ts"],
@@ -23325,12 +23619,16 @@
["es2017.string", "lib.es2017.string.d.ts"],
["es2017.intl", "lib.es2017.intl.d.ts"],
["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
+ ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
["es2018.intl", "lib.es2018.intl.d.ts"],
["es2018.promise", "lib.es2018.promise.d.ts"],
["es2018.regexp", "lib.es2018.regexp.d.ts"],
- ["esnext.array", "lib.esnext.array.d.ts"],
- ["esnext.symbol", "lib.esnext.symbol.d.ts"],
- ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"],
+ ["es2019.array", "lib.es2019.array.d.ts"],
+ ["es2019.string", "lib.es2019.string.d.ts"],
+ ["es2019.symbol", "lib.es2019.symbol.d.ts"],
+ ["esnext.array", "lib.es2019.array.d.ts"],
+ ["esnext.symbol", "lib.es2019.symbol.d.ts"],
+ ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
["esnext.intl", "lib.esnext.intl.d.ts"],
["esnext.bigint", "lib.esnext.bigint.d.ts"]
];
@@ -23476,14 +23774,15 @@
es2016: 3 /* ES2016 */,
es2017: 4 /* ES2017 */,
es2018: 5 /* ES2018 */,
- esnext: 6 /* ESNext */,
+ es2019: 6 /* ES2019 */,
+ esnext: 7 /* ESNext */,
}),
affectsSourceFile: true,
affectsModuleResolution: true,
paramType: ts.Diagnostics.VERSION,
showInSimplifiedHelpView: true,
category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT,
+ description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT,
},
{
name: "module",
@@ -23605,6 +23904,22 @@
description: ts.Diagnostics.Enable_project_compilation,
},
{
+ name: "incremental",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_incremental_compilation,
+ },
+ {
+ name: "tsBuildInfoFile",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE,
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
+ },
+ {
name: "removeComments",
type: "boolean",
showInSimplifiedHelpView: true,
@@ -25030,7 +25345,7 @@
}
function directoryOfCombinedPath(fileName, basePath) {
// Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
- // until consistient casing errors are reported
+ // until consistent casing errors are reported
return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
}
/**
@@ -27322,7 +27637,7 @@
return "__constructor" /* Constructor */;
case 165 /* FunctionType */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return "__call" /* Call */;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
@@ -27331,7 +27646,7 @@
return "__index" /* Index */;
case 255 /* ExportDeclaration */:
return "__export" /* ExportStar */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// json file should behave as
// module.exports = ...
return "export=" /* ExportEquals */;
@@ -27342,12 +27657,12 @@
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
case 151 /* 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 === 289 /* 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 === 294 /* 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;
@@ -27431,13 +27746,15 @@
message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
messageNeedsName_1 = false;
}
- if (symbol.declarations && symbol.declarations.length) {
+ var multipleDefaultExports_1 = false;
+ if (ts.length(symbol.declarations)) {
// If the current node is a default export of some sort, then check if
// there are any other default exports that we need to error on.
// 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;
+ multipleDefaultExports_1 = true;
}
else {
// This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
@@ -27448,14 +27765,22 @@
(node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) {
message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
messageNeedsName_1 = false;
+ multipleDefaultExports_1 = true;
}
}
}
- 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);
+ var declarationName_1 = ts.getNameOfDeclaration(node) || node;
+ var relatedInformation_1 = [];
+ ts.forEach(symbol.declarations, function (declaration, index) {
+ var decl = ts.getNameOfDeclaration(declaration) || declaration;
+ var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
+ file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo(diag, createDiagnosticForNode(declarationName_1, index === 0 ? ts.Diagnostics.Another_export_default_is_here : ts.Diagnostics.and_here)) : diag);
+ if (multipleDefaultExports_1) {
+ relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
+ }
+ });
+ var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
+ file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInformation_1)) : diag);
symbol = createSymbol(0 /* None */, name);
}
}
@@ -27571,7 +27896,7 @@
}
}
// We create a return control flow graph for IIFEs and constructors. For constructors
- // we use the return control flow graph in strict property intialization checks.
+ // we use the return control flow graph in strict property initialization checks.
currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined;
currentBreakTarget = undefined;
currentContinueTarget = undefined;
@@ -27586,7 +27911,7 @@
if (hasExplicitReturn)
node.flags |= 256 /* HasExplicitReturn */;
}
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
node.flags |= emitFlags;
}
if (currentReturnTarget) {
@@ -27730,12 +28055,12 @@
case 191 /* CallExpression */:
bindCallExpressionFlow(node);
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
bindJSDocTypeAlias(node);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
- case 279 /* SourceFile */: {
+ case 284 /* SourceFile */: {
bindEachFunctionsFirst(node.statements);
bind(node.endOfFileToken);
break;
@@ -28422,7 +28747,7 @@
case 243 /* EnumDeclaration */:
case 188 /* ObjectLiteralExpression */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 268 /* JsxAttributes */:
return 1 /* IsContainer */;
case 241 /* InterfaceDeclaration */:
@@ -28431,7 +28756,7 @@
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
return 1 /* IsContainer */ | 32 /* HasLocals */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
case 156 /* MethodDeclaration */:
if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
@@ -28444,8 +28769,8 @@
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
- case 289 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
case 165 /* FunctionType */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
@@ -28499,7 +28824,7 @@
// handlers to take care of declaring these child members.
case 244 /* ModuleDeclaration */:
return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return declareSourceFileMember(node, symbolFlags, symbolExcludes);
case 209 /* ClassExpression */:
case 240 /* ClassDeclaration */:
@@ -28507,7 +28832,7 @@
case 243 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 188 /* ObjectLiteralExpression */:
case 241 /* InterfaceDeclaration */:
case 268 /* JsxAttributes */:
@@ -28521,7 +28846,7 @@
case 166 /* ConstructorType */:
case 160 /* CallSignature */:
case 161 /* ConstructSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 162 /* IndexSignature */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
@@ -28531,9 +28856,9 @@
case 239 /* FunctionDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
- case 289 /* JSDocFunctionType */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 294 /* JSDocFunctionType */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
// All the children of these container types are never visible through another
@@ -28556,8 +28881,8 @@
: declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node) {
- var body = node.kind === 279 /* SourceFile */ ? node : node.body;
- if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
+ var body = node.kind === 284 /* SourceFile */ ? node : node.body;
+ if (body && (body.kind === 284 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
var stat = _a[_i];
if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) {
@@ -28691,7 +29016,7 @@
case 244 /* ModuleDeclaration */:
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalOrCommonJsModule(container)) {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
@@ -28829,7 +29154,7 @@
function checkStrictModeFunctionDeclaration(node) {
if (languageVersion < 2 /* ES2015 */) {
// Report error if function is not top level function declaration
- if (blockScopeContainer.kind !== 279 /* SourceFile */ &&
+ if (blockScopeContainer.kind !== 284 /* SourceFile */ &&
blockScopeContainer.kind !== 244 /* ModuleDeclaration */ &&
!ts.isFunctionLike(blockScopeContainer)) {
// We check first if the name is inside class declaration or class expression; if so give explicit message
@@ -29104,12 +29429,12 @@
case 159 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */);
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
case 166 /* ConstructorType */:
return bindFunctionOrConstructorType(node);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 181 /* MappedType */:
return bindAnonymousTypeWorker(node);
case 188 /* ObjectLiteralExpression */:
@@ -29168,7 +29493,7 @@
return bindExportDeclaration(node);
case 254 /* ExportAssignment */:
return bindExportAssignment(node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
updateStrictModeStatementList(node.statements);
return bindSourceFileIfExternalModule();
case 218 /* Block */:
@@ -29178,22 +29503,22 @@
// falls through
case 245 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
- case 299 /* JSDocParameterTag */:
- if (node.parent.kind === 293 /* JSDocSignature */) {
+ case 304 /* JSDocParameterTag */:
+ if (node.parent.kind === 298 /* JSDocSignature */) {
return bindParameter(node);
}
- if (node.parent.kind !== 292 /* JSDocTypeLiteral */) {
+ if (node.parent.kind !== 297 /* JSDocTypeLiteral */) {
break;
}
// falls through
- case 305 /* JSDocPropertyTag */:
+ case 310 /* JSDocPropertyTag */:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 293 /* JSDocOptionalType */ ?
4 /* Property */ | 16777216 /* Optional */ :
4 /* Property */;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
}
}
@@ -29365,9 +29690,14 @@
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 279 /* SourceFile */:
- // this.foo assignment in a source file
- // Do not bind. It would be nice to support this someday though.
+ case 284 /* SourceFile */:
+ // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
+ if (thisContainer.commonJsModuleIndicator) {
+ declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220414 /* FunctionScopedVariableExcludes */);
+ }
break;
default:
ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer));
@@ -29377,7 +29707,7 @@
if (node.expression.kind === 100 /* ThisKeyword */) {
bindThisPropertyAssignment(node);
}
- else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) {
+ else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 284 /* SourceFile */) {
if (ts.isPrototypeAccess(node.expression)) {
bindPrototypePropertyAssignment(node, node.parent);
}
@@ -29414,7 +29744,7 @@
}
function bindObjectDefinePropertyAssignment(node) {
var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
- var isToplevel = node.parent.parent.kind === 279 /* SourceFile */;
+ var isToplevel = node.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false);
bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
}
@@ -29481,8 +29811,8 @@
function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
var namespaceSymbol = lookupSymbolForPropertyAccess(name);
var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
- ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */
- : propertyAccess.parent.parent.kind === 279 /* SourceFile */;
+ ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 284 /* SourceFile */
+ : propertyAccess.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty);
bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
}
@@ -29620,7 +29950,7 @@
}
}
function bindParameter(node) {
- if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) {
+ if (node.kind === 304 /* JSDocParameterTag */ && container.kind !== 298 /* JSDocSignature */) {
return;
}
if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) {
@@ -29878,44 +30208,37 @@
ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
function computeCallExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
+ var callee = ts.skipOuterExpressions(node.expression);
var expression = node.expression;
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */
- || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) {
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) {
// If the this node contains a SpreadExpression, or is a super call, then it is an ES6
// node.
- transformFlags |= 192 /* AssertES2015 */;
- // super property or element accesses could be inside lambdas, etc, and need a captured `this`,
- // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor)
- if (expression.transformFlags & 67108864 /* ContainsSuper */) {
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 128 /* AssertES2015 */;
+ if (ts.isSuperProperty(callee)) {
+ transformFlags |= 2048 /* ContainsLexicalThis */;
}
}
if (expression.kind === 92 /* ImportKeyword */) {
- transformFlags |= 16777216 /* ContainsDynamicImport */;
- // A dynamic 'import()' call that contains a lexical 'this' will
- // require a captured 'this' when emitting down-level.
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- transformFlags |= 16384 /* ContainsCapturedLexicalThis */;
- }
+ transformFlags |= 524288 /* ContainsDynamicImport */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */;
}
function computeNewExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */) {
// If the this node contains a SpreadElementExpression then it is an ES6
// node.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */;
}
function computeBinaryExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -29923,20 +30246,20 @@
var leftKind = node.left.kind;
if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) {
// Destructuring object assignments with are ES2015 syntax
- // and possibly ESNext if they contain rest
- transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
+ // and possibly ES2018 if they contain rest
+ transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */;
}
else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) {
// Destructuring assignments are ES2015 syntax.
- transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
+ transformFlags |= 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */;
}
else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */
|| operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) {
// Exponentiation is ES2016 syntax.
- transformFlags |= 32 /* AssertES2016 */;
+ transformFlags |= 64 /* AssertES2016 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeParameter(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -29947,147 +30270,131 @@
// syntax.
if (node.questionToken
|| node.type
- || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
+ || (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
|| ts.isThisIdentifier(name)) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// If a parameter has an accessibility modifier, then it is TypeScript syntax.
if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
- transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */;
}
- // parameters with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // parameters with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a parameter has an initializer, a binding pattern or a dotDotDot token, then
// it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
- if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
- transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */;
+ if (subtreeFlags & 65536 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* ParameterExcludes */;
+ return transformFlags & ~536870912 /* ParameterExcludes */;
}
function computeParenthesizedExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
var expression = node.expression;
var expressionKind = expression.kind;
- var expressionTransformFlags = expression.transformFlags;
// 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 === 212 /* AsExpression */
|| expressionKind === 194 /* TypeAssertionExpression */) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- // If the expression of a ParenthesizedExpression is a destructuring assignment,
- // then the ParenthesizedExpression is a destructuring assignment.
- if (expressionTransformFlags & 1024 /* DestructuringAssignment */) {
- transformFlags |= 1024 /* DestructuringAssignment */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536872257 /* OuterExpressionExcludes */;
+ return transformFlags & ~536870912 /* OuterExpressionExcludes */;
}
function computeClassDeclaration(node, subtreeFlags) {
var transformFlags;
if (ts.hasModifier(node, 2 /* Ambient */)) {
// An ambient declaration is TypeScript syntax.
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
// A ClassDeclaration is ES6 syntax.
- transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// A class with a parameter property assignment, property initializer, computed property name, or decorator is
// TypeScript syntax.
// An exported declaration may be TypeScript syntax, but is handled by the visitor
// for a namespace declaration.
- if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */)
+ if ((subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */)
|| node.typeParameters) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~638121281 /* ClassExcludes */;
+ return transformFlags & ~536888320 /* ClassExcludes */;
}
function computeClassExpression(node, subtreeFlags) {
// A ClassExpression is ES6 syntax.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// A class with a parameter property assignment, property initializer, or decorator is
// TypeScript syntax.
- if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */
+ if (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */
|| node.typeParameters) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~638121281 /* ClassExcludes */;
+ return transformFlags & ~536888320 /* ClassExcludes */;
}
function computeHeritageClause(node, subtreeFlags) {
var transformFlags = subtreeFlags;
switch (node.token) {
case 86 /* ExtendsKeyword */:
// An `extends` HeritageClause is ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 109 /* ImplementsKeyword */:
// An `implements` HeritageClause is TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
break;
default:
ts.Debug.fail("Unexpected token for heritage clause");
break;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeCatchClause(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (!node.variableDeclaration) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 8 /* AssertES2019 */;
}
else if (ts.isBindingPattern(node.variableDeclaration.name)) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637797697 /* CatchClauseExcludes */;
+ return transformFlags & ~536879104 /* CatchClauseExcludes */;
}
function computeExpressionWithTypeArguments(node, subtreeFlags) {
// An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
// extends clause of a class.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// If an ExpressionWithTypeArguments contains type arguments, then it
// is TypeScript syntax.
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeConstructor(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// TypeScript-specific modifiers and overloads are TypeScript syntax
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* ConstructorExcludes */;
+ return transformFlags & ~537372672 /* ConstructorExcludes */;
}
function computeMethod(node, subtreeFlags) {
// A MethodDeclaration is ES6 syntax.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
// overloads are TypeScript syntax.
if (node.decorators
@@ -30096,21 +30403,21 @@
|| node.type
|| (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// An async method declaration is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* MethodOrAccessorExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */);
}
function computeAccessor(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -30121,25 +30428,25 @@
|| node.type
|| (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* MethodOrAccessorExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */);
}
function computePropertyDeclaration(node, subtreeFlags) {
// A PropertyDeclaration is TypeScript syntax.
- var transformFlags = subtreeFlags | 3 /* AssertTypeScript */;
+ var transformFlags = subtreeFlags | 1 /* AssertTypeScript */;
// If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor
// so that it handle the transformation.
if (node.initializer || ts.isComputedPropertyName(node.name)) {
- transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1024 /* ContainsTypeScriptClassSyntax */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~536872960 /* PropertyExcludes */);
}
function computeFunctionDeclaration(node, subtreeFlags) {
var transformFlags;
@@ -30148,42 +30455,36 @@
if (!body || (modifierFlags & 2 /* Ambient */)) {
// An ambient declaration is TypeScript syntax.
// A FunctionDeclaration without a body is an overload and is TypeScript syntax.
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
- transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */;
+ transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */;
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (modifierFlags & 2270 /* TypeScriptModifier */
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async function declaration is ES2017 syntax.
if (modifierFlags & 256 /* Async */) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If a FunctionDeclaration's subtree has marked the container as needing to capture the
- // lexical this, or the function contains parameters with initializers, then this node is
- // ES6 syntax.
- if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) {
- transformFlags |= 192 /* AssertES2015 */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a FunctionDeclaration is generator function and is the body of a
// transformed async function, then this node can be transformed to a
// down-level generator.
- // Currently we do not support transforming any other generator fucntions
+ // Currently we do not support transforming any other generator functions
// down level.
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653620545 /* FunctionExcludes */;
+ return transformFlags & ~537373696 /* FunctionExcludes */;
}
function computeFunctionExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -30192,181 +30493,161 @@
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async function expression is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
- // function expressions with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If a FunctionExpression's subtree has marked the container as needing to capture the
- // lexical this, or the function contains parameters with initializers, then this node is
- // ES6 syntax.
- if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) {
- transformFlags |= 192 /* AssertES2015 */;
+ // function expressions with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a FunctionExpression is generator function and is the body of a
// transformed async function, then this node can be transformed to a
// down-level generator.
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653620545 /* FunctionExcludes */;
+ return transformFlags & ~537373696 /* FunctionExcludes */;
}
function computeArrowFunction(node, subtreeFlags) {
// An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async arrow function is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= 16 /* AssertES2017 */;
+ transformFlags |= 32 /* AssertES2017 */;
}
- // arrow functions with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If an ArrowFunction contains a lexical this, its container must capture the lexical this.
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- transformFlags |= 16384 /* ContainsCapturedLexicalThis */;
+ // arrow functions with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653604161 /* ArrowFunctionExcludes */;
+ return transformFlags & ~537371648 /* ArrowFunctionExcludes */;
}
function computePropertyAccess(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// If a PropertyAccessExpression starts with a super keyword, then it is
// ES6 syntax, and requires a lexical `this` binding.
- if (transformFlags & 33554432 /* Super */) {
- transformFlags ^= 33554432 /* Super */;
+ if (node.expression.kind === 98 /* SuperKeyword */) {
// super inside of an async function requires hoisting the super access (ES2017).
- // same for super inside of an async generator, which is ESNext.
- transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */;
+ // same for super inside of an async generator, which is ES2018.
+ transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~570426689 /* PropertyAccessExcludes */;
+ return transformFlags & ~536870912 /* PropertyAccessExcludes */;
}
function computeElementAccess(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- var expression = node.expression;
- var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing
// If an ElementAccessExpression starts with a super keyword, then it is
// ES6 syntax, and requires a lexical `this` binding.
- if (expressionFlags & 33554432 /* Super */) {
- transformFlags &= ~33554432 /* Super */;
+ if (node.expression.kind === 98 /* SuperKeyword */) {
// super inside of an async function requires hoisting the super access (ES2017).
- // same for super inside of an async generator, which is ESNext.
- transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */;
+ // same for super inside of an async generator, which is ES2018.
+ transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~570426689 /* PropertyAccessExcludes */;
+ return transformFlags & ~536870912 /* PropertyAccessExcludes */;
}
function computeVariableDeclaration(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- // A VariableDeclaration containing ObjectRest is ESNext syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally?
+ // A VariableDeclaration containing ObjectRest is ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// Type annotations are TypeScript syntax.
if (node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeVariableStatement(node, subtreeFlags) {
var transformFlags;
var declarationListTransformFlags = node.declarationList.transformFlags;
// An ambient declaration is TypeScript syntax.
if (ts.hasModifier(node, 2 /* Ambient */)) {
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
transformFlags = subtreeFlags;
- if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) {
- transformFlags |= 192 /* AssertES2015 */;
+ if (declarationListTransformFlags & 65536 /* ContainsBindingPattern */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeLabeledStatement(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
- if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */
+ if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */
&& ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeImportEquals(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// An ImportEqualsDeclaration with a namespace reference is TypeScript.
if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeExpressionStatement(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- // If the expression of an expression statement is a destructuring assignment,
- // then we treat the statement as ES6 so that we can indicate that we do not
- // need to hold on to the right-hand side.
- if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) {
- transformFlags |= 192 /* AssertES2015 */;
- }
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeModuleDeclaration(node, subtreeFlags) {
- var transformFlags = 3 /* AssertTypeScript */;
+ var transformFlags = 1 /* AssertTypeScript */;
var modifierFlags = ts.getModifierFlags(node);
if ((modifierFlags & 2 /* Ambient */) === 0) {
transformFlags |= subtreeFlags;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~647001409 /* ModuleExcludes */;
+ return transformFlags & ~537168896 /* ModuleExcludes */;
}
function computeVariableDeclarationList(node, subtreeFlags) {
- var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */;
- if (subtreeFlags & 2097152 /* ContainsBindingPattern */) {
- transformFlags |= 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */;
+ if (subtreeFlags & 65536 /* ContainsBindingPattern */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
// If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
if (node.flags & 3 /* BlockScoped */) {
- transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */;
+ transformFlags |= 128 /* AssertES2015 */ | 32768 /* ContainsBlockScopedBinding */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~639894849 /* VariableDeclarationListExcludes */;
+ return transformFlags & ~536944640 /* VariableDeclarationListExcludes */;
}
function computeOther(node, kind, subtreeFlags) {
// Mark transformations needed for each node
var transformFlags = subtreeFlags;
- var excludeFlags = 637535553 /* NodeExcludes */;
+ var excludeFlags = 536870912 /* NodeExcludes */;
switch (kind) {
case 121 /* AsyncKeyword */:
case 201 /* AwaitExpression */:
- // async/await is ES2017 syntax, but may be ESNext syntax (for async generators)
- transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */;
+ // async/await is ES2017 syntax, but may be ES2018 syntax (for async generators)
+ transformFlags |= 16 /* AssertES2018 */ | 32 /* AssertES2017 */;
break;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
// These nodes are TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
- excludeFlags = 536872257 /* OuterExpressionExcludes */;
+ transformFlags |= 1 /* AssertTypeScript */;
+ excludeFlags = 536870912 /* OuterExpressionExcludes */;
break;
case 115 /* PublicKeyword */:
case 113 /* PrivateKeyword */:
@@ -30379,7 +30660,7 @@
case 213 /* NonNullExpression */:
case 133 /* ReadonlyKeyword */:
// These nodes are TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
break;
case 260 /* JsxElement */:
case 261 /* JsxSelfClosingElement */:
@@ -30394,7 +30675,7 @@
case 269 /* JsxSpreadAttribute */:
case 270 /* JsxExpression */:
// These nodes are Jsx syntax.
- transformFlags |= 4 /* AssertJsx */;
+ transformFlags |= 2 /* AssertJsx */;
break;
case 14 /* NoSubstitutionTemplateLiteral */:
case 15 /* TemplateHead */:
@@ -30406,32 +30687,32 @@
case 116 /* StaticKeyword */:
case 214 /* MetaProperty */:
// These nodes are ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 10 /* StringLiteral */:
if (node.hasExtendedUnicodeEscape) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
case 8 /* NumericLiteral */:
if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
case 9 /* BigIntLiteral */:
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 4 /* AssertESNext */;
break;
case 227 /* ForOfStatement */:
// This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
if (node.awaitModifier) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 16 /* AssertES2018 */;
}
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 207 /* YieldExpression */:
// This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
// generator).
- transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */;
+ transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 131072 /* ContainsYield */;
break;
case 120 /* AnyKeyword */:
case 135 /* NumberKeyword */:
@@ -30472,115 +30753,93 @@
case 182 /* LiteralType */:
case 247 /* NamespaceExportDeclaration */:
// Types and signatures are TypeScript syntax, and exclude all other facts.
- transformFlags = 3 /* AssertTypeScript */;
- excludeFlags = -3 /* TypeExcludes */;
+ transformFlags = 1 /* AssertTypeScript */;
+ excludeFlags = -2 /* TypeExcludes */;
break;
case 149 /* ComputedPropertyName */:
// Even though computed property names are ES6, we don't treat them as such.
// This is so that they can flow through PropertyName transforms unaffected.
// Instead, we mark the container as ES6, so that it can properly handle the transform.
- transformFlags |= 524288 /* ContainsComputedPropertyName */;
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- // A computed method name like `[this.getName()](x: string) { ... }` needs to
- // distinguish itself from the normal case of a method body containing `this`:
- // `this` inside a method doesn't need to be rewritten (the method provides `this`),
- // whereas `this` inside a computed name *might* need to be rewritten if the class/object
- // is inside an arrow function:
- // `_this = this; () => class K { [_this.getName()]() { ... } }`
- // To make this distinction, use ContainsLexicalThisInComputedPropertyName
- // instead of ContainsLexicalThis for computed property names
- transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */;
- }
+ transformFlags |= 16384 /* ContainsComputedPropertyName */;
break;
case 208 /* SpreadElement */:
- transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */;
+ transformFlags |= 128 /* AssertES2015 */ | 4096 /* ContainsRestOrSpread */;
break;
case 277 /* SpreadAssignment */:
- transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */;
+ transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */;
break;
case 98 /* SuperKeyword */:
// This node is ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */;
- excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super`
+ transformFlags |= 128 /* AssertES2015 */;
+ excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super`
break;
case 100 /* ThisKeyword */:
// Mark this node and its ancestors as containing a lexical `this` keyword.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 2048 /* ContainsLexicalThis */;
break;
case 184 /* ObjectBindingPattern */:
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */;
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */;
}
- excludeFlags = 637666625 /* BindingPatternExcludes */;
+ excludeFlags = 536875008 /* BindingPatternExcludes */;
break;
case 185 /* ArrayBindingPattern */:
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- excludeFlags = 637666625 /* BindingPatternExcludes */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */;
+ excludeFlags = 536875008 /* BindingPatternExcludes */;
break;
case 186 /* BindingElement */:
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
if (node.dotDotDotToken) {
- transformFlags |= 131072 /* ContainsRestOrSpread */;
+ transformFlags |= 4096 /* ContainsRestOrSpread */;
}
break;
case 152 /* Decorator */:
// This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */;
break;
case 188 /* ObjectLiteralExpression */:
- excludeFlags = 638358849 /* ObjectLiteralExcludes */;
- if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) {
+ excludeFlags = 536896512 /* ObjectLiteralExcludes */;
+ if (subtreeFlags & 16384 /* ContainsComputedPropertyName */) {
// If an ObjectLiteralExpression contains a ComputedPropertyName, then it
// is an ES6 node.
- transformFlags |= 192 /* AssertES2015 */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 128 /* AssertES2015 */;
}
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
// If an ObjectLiteralExpression contains a spread element, then it
- // is an ES next node.
- transformFlags |= 8 /* AssertESNext */;
+ // is an ES2018 node.
+ transformFlags |= 16 /* AssertES2018 */;
}
break;
case 187 /* ArrayLiteralExpression */:
- case 192 /* NewExpression */:
- excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */;
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
- // If the this node contains a SpreadExpression, then it is an ES6
- // node.
- transformFlags |= 192 /* AssertES2015 */;
- }
+ excludeFlags = 536875008 /* ArrayLiteralOrCallOrNewExcludes */;
break;
case 223 /* DoStatement */:
case 224 /* WhileStatement */:
case 225 /* ForStatement */:
case 226 /* ForInStatement */:
// A loop containing a block scoped binding *may* need to be transformed from ES6.
- if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) {
- transformFlags |= 192 /* AssertES2015 */;
+ if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
- case 279 /* SourceFile */:
- if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) {
- transformFlags |= 192 /* AssertES2015 */;
- }
+ case 284 /* SourceFile */:
break;
case 230 /* ReturnStatement */:
- // Return statements may require an `await` in ESNext.
- transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */;
+ // Return statements may require an `await` in ES2018.
+ transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */ | 16 /* AssertES2018 */;
break;
case 228 /* ContinueStatement */:
case 229 /* BreakStatement */:
- transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */;
+ transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */;
break;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
return transformFlags & ~excludeFlags;
}
+ function propagatePropertyNameFlags(node, transformFlags) {
+ return transformFlags | (node.transformFlags & 2048 /* PropertyNamePropagatingFlags */);
+ }
/**
* Gets the transform flags to exclude when unioning the transform flags of a subtree.
*
@@ -30590,33 +30849,33 @@
*/
function getTransformFlagsSubtreeExclusions(kind) {
if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) {
- return -3 /* TypeExcludes */;
+ return -2 /* TypeExcludes */;
}
switch (kind) {
case 191 /* CallExpression */:
case 192 /* NewExpression */:
case 187 /* ArrayLiteralExpression */:
- return 637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return 536875008 /* ArrayLiteralOrCallOrNewExcludes */;
case 244 /* ModuleDeclaration */:
- return 647001409 /* ModuleExcludes */;
+ return 537168896 /* ModuleExcludes */;
case 151 /* Parameter */:
- return 637535553 /* ParameterExcludes */;
+ return 536870912 /* ParameterExcludes */;
case 197 /* ArrowFunction */:
- return 653604161 /* ArrowFunctionExcludes */;
+ return 537371648 /* ArrowFunctionExcludes */;
case 196 /* FunctionExpression */:
case 239 /* FunctionDeclaration */:
- return 653620545 /* FunctionExcludes */;
+ return 537373696 /* FunctionExcludes */;
case 238 /* VariableDeclarationList */:
- return 639894849 /* VariableDeclarationListExcludes */;
+ return 536944640 /* VariableDeclarationListExcludes */;
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
- return 638121281 /* ClassExcludes */;
+ return 536888320 /* ClassExcludes */;
case 157 /* Constructor */:
- return 653616449 /* ConstructorExcludes */;
+ return 537372672 /* ConstructorExcludes */;
case 156 /* MethodDeclaration */:
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
- return 653616449 /* MethodOrAccessorExcludes */;
+ return 537372672 /* MethodOrAccessorExcludes */;
case 120 /* AnyKeyword */:
case 135 /* NumberKeyword */:
case 146 /* BigIntKeyword */:
@@ -30634,25 +30893,25 @@
case 162 /* IndexSignature */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- return -3 /* TypeExcludes */;
+ return -2 /* TypeExcludes */;
case 188 /* ObjectLiteralExpression */:
- return 638358849 /* ObjectLiteralExcludes */;
+ return 536896512 /* ObjectLiteralExcludes */;
case 274 /* CatchClause */:
- return 637797697 /* CatchClauseExcludes */;
+ return 536879104 /* CatchClauseExcludes */;
case 184 /* ObjectBindingPattern */:
case 185 /* ArrayBindingPattern */:
- return 637666625 /* BindingPatternExcludes */;
+ return 536875008 /* BindingPatternExcludes */;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
case 195 /* ParenthesizedExpression */:
case 98 /* SuperKeyword */:
- return 536872257 /* OuterExpressionExcludes */;
+ return 536870912 /* OuterExpressionExcludes */;
case 189 /* PropertyAccessExpression */:
case 190 /* ElementAccessExpression */:
- return 570426689 /* PropertyAccessExcludes */;
+ return 536870912 /* PropertyAccessExcludes */;
default:
- return 637535553 /* NodeExcludes */;
+ return 536870912 /* NodeExcludes */;
}
}
ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
@@ -30901,6 +31160,7 @@
var enumCount = 0;
var instantiationDepth = 0;
var constraintDepth = 0;
+ var currentNode;
var emptySymbols = ts.createSymbolTable();
var identityMapper = ts.identity;
var compilerOptions = host.getCompilerOptions();
@@ -30917,8 +31177,14 @@
var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
var emitResolver = createResolver();
var nodeBuilder = createNodeBuilder();
+ var globals = ts.createSymbolTable();
var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
undefinedSymbol.declarations = [];
+ var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
+ globalThisSymbol.exports = globals;
+ globalThisSymbol.valueDeclaration = ts.createNode(72 /* Identifier */);
+ globalThisSymbol.valueDeclaration.escapedText = "globalThis";
+ globals.set(globalThisSymbol.escapedName, globalThisSymbol);
var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
var requireSymbol = createSymbol(4 /* Property */, "require");
/** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
@@ -31048,11 +31314,13 @@
isContextSensitive: isContextSensitive,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 0 /* Normal */);
},
getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */);
},
+ getExpandedParameters: getExpandedParameters,
+ hasEffectiveRestParameter: hasEffectiveRestParameter,
getConstantValue: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
return node ? getConstantValue(node) : undefined;
@@ -31114,6 +31382,8 @@
getNeverType: function () { return neverType; },
isSymbolAccessible: isSymbolAccessible,
getObjectFlags: ts.getObjectFlags,
+ isArrayType: isArrayType,
+ isTupleType: isTupleType,
isArrayLikeType: isArrayLikeType,
isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
@@ -31129,9 +31399,9 @@
getAccessibleSymbolChain: getAccessibleSymbolChain,
getTypePredicateOfSignature: getTypePredicateOfSignature,
resolveExternalModuleSymbol: resolveExternalModuleSymbol,
- tryGetThisTypeAt: function (node) {
+ tryGetThisTypeAt: function (node, includeGlobalThis) {
node = ts.getParseTreeNode(node);
- return node && tryGetThisTypeAt(node);
+ return node && tryGetThisTypeAt(node, includeGlobalThis);
},
getTypeArgumentConstraint: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
@@ -31178,10 +31448,10 @@
},
getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
};
- function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) {
+ function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
apparentArgumentCount = argumentCount;
- var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined;
+ var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
apparentArgumentCount = undefined;
return res;
}
@@ -31190,6 +31460,7 @@
var intersectionTypes = ts.createMap();
var literalTypes = ts.createMap();
var indexedAccessTypes = ts.createMap();
+ var conditionalTypes = ts.createMap();
var evolvingArrayTypes = [];
var undefinedProperties = ts.createMap();
var unknownSymbol = createSymbol(4 /* Property */, "unknown");
@@ -31200,9 +31471,9 @@
var errorType = createIntrinsicType(1 /* Any */, "error");
var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
- var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined");
+ var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */);
var nullType = createIntrinsicType(65536 /* Null */, "null");
- var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null");
+ var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */);
var stringType = createIntrinsicType(4 /* String */, "string");
var numberType = createIntrinsicType(8 /* Number */, "number");
var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
@@ -31228,6 +31499,7 @@
var voidType = createIntrinsicType(16384 /* Void */, "void");
var neverType = createIntrinsicType(131072 /* Never */, "never");
var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
+ var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */);
var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
@@ -31244,7 +31516,7 @@
var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
// The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
// in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
- anyFunctionType.flags |= 536870912 /* ContainsAnyFunctionType */;
+ anyFunctionType.objectFlags |= 524288 /* NonInferrableType */;
var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
@@ -31258,7 +31530,6 @@
var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
- var globals = ts.createSymbolTable();
/** Key is "/path/to/a.ts|/path/to/b.ts". */
var amalgamatedDuplicates;
var reverseMappedCache = ts.createMap();
@@ -31457,9 +31728,11 @@
var CheckMode;
(function (CheckMode) {
CheckMode[CheckMode["Normal"] = 0] = "Normal";
- CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive";
+ CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
- CheckMode[CheckMode["Contextual"] = 3] = "Contextual";
+ CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
+ CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
+ CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
})(CheckMode || (CheckMode = {}));
var CallbackCheck;
(function (CallbackCheck) {
@@ -31546,18 +31819,6 @@
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)
@@ -31737,7 +31998,7 @@
err.relatedInformation = err.relatedInformation || [];
if (ts.length(err.relatedInformation) >= 5)
continue;
- addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here));
+ ts.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) {
@@ -31815,7 +32076,7 @@
return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
}
function isGlobalSourceFile(node) {
- return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
+ return node.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning) {
@@ -31989,7 +32250,7 @@
// - 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 & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) {
+ if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 296 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -32031,14 +32292,14 @@
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
isInExternalModule = true;
// falls through
case 244 /* ModuleDeclaration */:
var moduleExports = getSymbolOfNode(location).exports;
- if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) {
+ if (location.kind === 284 /* 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 */)) {
@@ -32206,12 +32467,18 @@
// @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
// }
//
- if (location.parent && ts.isClassElement(location.parent)) {
+ // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
+ //
+ // type T = number;
+ // declare function y(x: T): any;
+ // @param(1 as T) // <-- T should resolve to the type alias outside of class C
+ // class C<T> {}
+ if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 240 /* ClassDeclaration */)) {
location = location.parent;
}
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
// js type aliases do not resolve names from their host, so skip past it
location = ts.getJSDocHost(location);
break;
@@ -32230,7 +32497,7 @@
}
if (!result) {
if (lastLocation) {
- ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */);
+ ts.Debug.assert(lastLocation.kind === 284 /* SourceFile */);
if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
return lastLocation.symbol;
}
@@ -32253,7 +32520,8 @@
!checkAndReportErrorForExtendingInterface(errorLocation) &&
!checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
!checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
- !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) {
+ !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
+ !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
var suggestion = void 0;
if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
@@ -32261,7 +32529,7 @@
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));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
}
}
}
@@ -32418,6 +32686,16 @@
}
return false;
}
+ function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
+ if (meaning & (67897832 /* Type */ & ~1920 /* Namespace */)) {
+ var symbol = resolveSymbol(resolveName(errorLocation, name, ~67897832 /* Type */ & 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
+ error(errorLocation, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here, ts.unescapeLeadingUnderscores(name));
+ return true;
+ }
+ }
+ return false;
+ }
function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) {
if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") {
@@ -32426,7 +32704,7 @@
}
var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
- var message = (name === "Promise" || name === "Symbol")
+ var message = isES2015OrLaterConstructorName(name)
? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later
: ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
@@ -32435,6 +32713,18 @@
}
return false;
}
+ function isES2015OrLaterConstructorName(n) {
+ switch (n) {
+ case "Promise":
+ case "Symbol":
+ case "Map":
+ case "WeakMap":
+ case "Set":
+ case "WeakSet":
+ return true;
+ }
+ return false;
+ }
function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) {
var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
@@ -32477,7 +32767,7 @@
}
}
if (diagnosticMessage) {
- addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
+ ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
}
}
}
@@ -32661,7 +32951,7 @@
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));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
}
}
else {
@@ -32981,22 +33271,14 @@
return undefined;
}
if (moduleNotFoundError) {
- // For relative paths, see if this was possibly a projectReference redirect
- if (ts.pathIsRelative(moduleReference)) {
- var sourceFile_1 = ts.getSourceFileOfNode(location);
- var redirects = sourceFile_1.redirectedReferences;
- if (redirects) {
- var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName));
- for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) {
- var ext = _a[_i];
- var probePath = normalizedTargetPath + ext;
- if (redirects.indexOf(probePath) >= 0) {
- error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath);
+ // See if this was possibly a projectReference redirect
+ if (resolvedModule) {
+ var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
+ if (redirect) {
+ error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
return undefined;
}
}
- }
- }
if (resolutionDiagnostic) {
error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
}
@@ -33063,7 +33345,7 @@
function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) {
var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
if (!dontResolveAlias && symbol) {
- if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) {
+ if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 284 /* SourceFile */)) {
var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
? "allowSyntheticDefaultImports"
: "esModuleInterop";
@@ -33336,9 +33618,11 @@
result.id = typeCount;
return result;
}
- function createIntrinsicType(kind, intrinsicName) {
+ function createIntrinsicType(kind, intrinsicName, objectFlags) {
+ if (objectFlags === void 0) { objectFlags = 0; }
var type = createType(kind);
type.intrinsicName = intrinsicName;
+ type.objectFlags = objectFlags;
return type;
}
function createBooleanType(trueFalseTypes) {
@@ -33409,7 +33693,7 @@
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
@@ -33649,10 +33933,10 @@
return node && getSymbolOfNode(node);
}
function hasExternalModuleSymbol(declaration) {
- return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isAmbientModule(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
- return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
var aliasesToMakeVisible;
@@ -34021,8 +34305,8 @@
context.inferTypeParameters = type.root.inferTypeParameters;
var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
context.inferTypeParameters = saveInferTypeParameters;
- var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context);
- var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context);
+ var trueTypeNode = typeToTypeNodeHelper(type.trueType, context);
+ var falseTypeNode = typeToTypeNodeHelper(type.falseType, context);
context.approximateLength += 15;
return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
}
@@ -34109,7 +34393,7 @@
var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
(symbol.parent || // is exported function symbol
ts.forEach(symbol.declarations, function (declaration) {
- return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
+ return declaration.parent.kind === 284 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
// typeof is allowed only for static/non local functions
@@ -34149,13 +34433,14 @@
}
function typeReferenceToTypeNode(type) {
var typeArguments = type.typeArguments || ts.emptyArray;
- if (type.target === globalArrayType) {
+ if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
if (context.flags & 2 /* WriteArrayAsGenericType */) {
var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
- return ts.createTypeReferenceNode("Array", [typeArgumentNode]);
+ return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
}
var elementType = typeToTypeNodeHelper(typeArguments[0], context);
- return ts.createArrayTypeNode(elementType);
+ var arrayType = ts.createArrayTypeNode(elementType);
+ return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, arrayType);
}
else if (type.target.objectFlags & 8 /* Tuple */) {
if (typeArguments.length > 0) {
@@ -34168,11 +34453,13 @@
ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
ts.createOptionalTypeNode(tupleConstituentNodes[i]);
}
- return ts.createTupleTypeNode(tupleConstituentNodes);
+ var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes);
+ return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
}
}
if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
- return ts.createTupleTypeNode([]);
+ var tupleTypeNode = ts.createTupleTypeNode([]);
+ return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
}
context.encounteredError = true;
return undefined; // TODO: GH#18217
@@ -34336,7 +34623,7 @@
context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
context.enclosingDeclaration = saveEnclosingDeclaration;
var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined;
- if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) {
+ if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
var signatures = getSignaturesOfType(propertyType, 0 /* Call */);
for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
var signature = signatures_1[_i];
@@ -34472,7 +34759,7 @@
var savedContextFlags = context.flags;
context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
- type.symbol.declarations[0] &&
+ type.symbol.declarations && type.symbol.declarations[0] &&
ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
typeParameterShadowsNameInScope(type, context);
var name = shouldUseGeneratedName
@@ -34491,7 +34778,7 @@
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */);
if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
- parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */);
+ parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 304 /* JSDocParameterTag */);
}
var parameterType = getTypeOfSymbol(parameterSymbol);
if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
@@ -34649,7 +34936,7 @@
return top;
}
function getSpecifierForModuleSymbol(symbol, context) {
- var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */);
+ var file = ts.getDeclarationOfKind(symbol, 284 /* SourceFile */);
if (file && file.moduleName !== undefined) {
// Use the amd name if it is available
return file.moduleName;
@@ -34902,7 +35189,7 @@
ts.isExternalModuleAugmentation(node.parent.parent);
}
function isDefaultBindingContext(location) {
- return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location);
+ return location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location);
}
function getNameOfSymbolFromNameType(symbol, context) {
var nameType = symbol.nameType;
@@ -34979,8 +35266,8 @@
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* 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));
@@ -35007,7 +35294,7 @@
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 !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
+ !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 284 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
return isGlobalSourceFile(parent);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
@@ -35049,7 +35336,7 @@
// Type parameters are always visible
case 150 /* TypeParameter */:
// Source file and namespace export are always visible
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 247 /* NamespaceExportDeclaration */:
return true;
// Export assignments do not create name bindings outside the module
@@ -35228,7 +35515,7 @@
if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
&& !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
&& isSpreadableProperty(prop)) {
- members.set(prop.escapedName, getSpreadSymbol(prop));
+ members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
}
}
var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
@@ -35297,17 +35584,8 @@
function getTypeForBindingElement(declaration) {
var pattern = declaration.parent;
var parentType = getTypeForBindingElementParent(pattern.parent);
- // If parent has the unknown (error) type, then so does this binding element
- if (parentType === errorType) {
- return errorType;
- }
- // If no type was specified or inferred for parent,
- // infer from the initializer of the binding element if one is present.
- // Otherwise, go with the undefined type of the parent.
- if (!parentType) {
- return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType;
- }
- if (isTypeAny(parentType)) {
+ // If no type or an any type was inferred for parent, infer that for the binding element
+ if (!parentType || isTypeAny(parentType)) {
return parentType;
}
// Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
@@ -35389,6 +35667,11 @@
if (optional === void 0) { optional = true; }
return strictNullChecks && optional ? getOptionalType(type) : type;
}
+ function isParameterOfContextuallyTypedFunction(node) {
+ return node.kind === 151 /* Parameter */ &&
+ (node.parent.kind === 196 /* FunctionExpression */ || node.parent.kind === 197 /* ArrowFunction */) &&
+ !!getContextualType(node.parent);
+ }
// Return the inferred type for a variable, parameter, or property declaration
function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
// A variable declared in a for..in statement is of type string, or of type keyof T when the
@@ -35464,8 +35747,9 @@
return containerObjectType;
}
}
- // Use the type of the initializer expression if one is present
- if (declaration.initializer) {
+ // Use the type of the initializer expression if one is present and the declaration is
+ // not a parameter of a contextually typed function
+ if (declaration.initializer && !isParameterOfContextuallyTypedFunction(declaration)) {
var type = checkDeclarationInitializer(declaration);
return addOptionality(type, isOptional);
}
@@ -35474,8 +35758,9 @@
// I.e <Elem attr /> is sugar for <Elem attr={true} />
return trueType;
}
- // If the declaration specifies a binding pattern, use the type implied by the binding pattern
- if (ts.isBindingPattern(declaration.name)) {
+ // If the declaration specifies a binding pattern and is not a parameter of a contextually
+ // typed function, use the type implied by the binding pattern
+ if (ts.isBindingPattern(declaration.name) && !isParameterOfContextuallyTypedFunction(declaration)) {
return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
}
// No type specified and nothing can be inferred
@@ -35531,7 +35816,7 @@
definedInConstructor = true;
}
}
- var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217
+ var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
type = getUnionType(sourceTypes, 2 /* Subtype */);
}
var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
@@ -35682,7 +35967,7 @@
function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
var members = ts.createSymbolTable();
var stringIndexInfo;
- var objectFlags = 128 /* ObjectLiteral */;
+ var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
ts.forEach(pattern.elements, function (e) {
var name = e.propertyName || e.name;
if (e.dotDotDotToken) {
@@ -35703,7 +35988,6 @@
members.set(symbol.escapedName, symbol);
});
var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
- result.flags |= 268435456 /* ContainsObjectLiteral */;
result.objectFlags |= objectFlags;
if (includePatternInType) {
result.pattern = pattern;
@@ -35787,7 +36071,16 @@
}
function getTypeOfVariableOrParameterOrProperty(symbol) {
var links = getSymbolLinks(symbol);
- return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol));
+ if (!links.type) {
+ var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
+ // For a contextually typed parameter it is possible that a type has already
+ // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
+ // to preserve this type.
+ if (!links.type) {
+ links.type = type;
+ }
+ }
+ return links.type;
}
function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
// Handle prototype property
@@ -35820,19 +36113,19 @@
}
return type_1;
}
- if (declaration.kind === 254 /* ExportAssignment */) {
- return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
- }
// Handle variable, parameter or property
if (!pushTypeResolution(symbol, 0 /* Type */)) {
// Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
if (symbol.flags & 512 /* ValueModule */) {
return getTypeOfFuncClassEnumModule(symbol);
}
- return errorType;
+ return reportCircularityError(symbol);
}
var type;
- if (ts.isInJSFile(declaration) &&
+ if (declaration.kind === 254 /* ExportAssignment */) {
+ type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
+ }
+ else if (ts.isInJSFile(declaration) &&
(ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) {
type = getWidenedTypeFromAssignmentDeclaration(symbol);
}
@@ -35887,7 +36180,7 @@
if (symbol.flags & 512 /* ValueModule */) {
return getTypeOfFuncClassEnumModule(symbol);
}
- type = reportCircularityError(symbol);
+ return reportCircularityError(symbol);
}
return type;
}
@@ -36065,15 +36358,19 @@
return links.type;
}
function reportCircularityError(symbol) {
+ var declaration = symbol.valueDeclaration;
// Check if variable has type annotation that circularly references the variable itself
- if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) {
+ if (ts.getEffectiveTypeAnnotationNode(declaration)) {
error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
return errorType;
}
- // Otherwise variable has initializer that circularly references the variable itself
- if (noImplicitAny) {
+ // Check if variable has initializer that circularly references the variable itself
+ if (noImplicitAny && (declaration.kind !== 151 /* Parameter */ || declaration.initializer)) {
error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
}
+ // Circularities could also result from parameters in function expressions that end up
+ // having themselves as contextual types following type argument inference. In those cases
+ // we have already reported an implicit any error so we don't report anything here.
return anyType;
}
function getTypeOfSymbol(symbol) {
@@ -36149,15 +36446,15 @@
case 155 /* MethodSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 308 /* JSDocTemplateTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 181 /* MappedType */:
case 175 /* ConditionalType */:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -36278,7 +36575,7 @@
ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
}
}
- addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
+ ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
}
return type.resolvedBaseConstructorType = errorType;
}
@@ -36289,7 +36586,7 @@
function getBaseTypes(type) {
if (!type.resolvedBaseTypes) {
if (type.objectFlags & 8 /* Tuple */) {
- type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))];
+ type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)];
}
else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
if (type.symbol.flags & 32 /* Class */) {
@@ -36654,7 +36951,7 @@
}
return false;
}
- /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */
+ /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
function isThislessTypeParameter(node) {
var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
return !constraint || isThislessType(constraint);
@@ -36697,6 +36994,8 @@
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
case 157 /* Constructor */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
return isThislessFunctionLikeDeclaration(declaration);
}
}
@@ -37028,8 +37327,18 @@
return sig;
}
function cloneSignature(sig) {
- return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
+ var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
/*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes);
+ result.target = sig.target;
+ result.mapper = sig.mapper;
+ return result;
+ }
+ function createUnionSignature(signature, unionSignatures) {
+ var result = cloneSignature(signature);
+ result.unionSignatures = unionSignatures;
+ result.target = undefined;
+ result.mapper = undefined;
+ return result;
}
function getExpandedParameters(sig) {
if (sig.hasRestParameter) {
@@ -37138,9 +37447,8 @@
var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */);
thisParameter = createSymbolWithType(signature.thisParameter, thisType);
}
- s = cloneSignature(signature);
+ s = createUnionSignature(signature, unionSignatures);
s.thisParameter = thisParameter;
- s.unionSignatures = unionSignatures;
}
(result || (result = [])).push(s);
}
@@ -37255,13 +37563,22 @@
function unionSpreadIndexInfos(info1, info2) {
return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
}
- function includeMixinType(type, types, index) {
+ function findMixins(types) {
+ var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
+ var mixinFlags = ts.map(types, isMixinConstructorType);
+ if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
+ var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
+ mixinFlags[firstMixinIndex] = false;
+ }
+ return mixinFlags;
+ }
+ function includeMixinType(type, types, mixinFlags, index) {
var mixedTypes = [];
for (var i = 0; i < types.length; i++) {
if (i === index) {
mixedTypes.push(type);
}
- else if (isMixinConstructorType(types[i])) {
+ else if (mixinFlags[i]) {
mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
}
}
@@ -37275,7 +37592,8 @@
var stringIndexInfo;
var numberIndexInfo;
var types = type.types;
- var mixinCount = ts.countWhere(types, isMixinConstructorType);
+ var mixinFlags = findMixins(types);
+ var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
var _loop_6 = function (i) {
var t = type.types[i];
// When an intersection type contains mixin constructor types, the construct signatures from
@@ -37283,12 +37601,12 @@
// other construct signatures in the intersection type. For example, the intersection type
// '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
// 'new(s: string) => A & B'.
- if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) {
+ if (!mixinFlags[i]) {
var signatures = getSignaturesOfType(t, 1 /* Construct */);
if (signatures.length && mixinCount > 0) {
signatures = ts.map(signatures, function (s) {
var clone = cloneSignature(s);
- clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i);
+ clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
return clone;
});
}
@@ -37332,6 +37650,15 @@
var stringIndexInfo = void 0;
if (symbol.exports) {
members = getExportsOfSymbol(symbol);
+ if (symbol === globalThisSymbol) {
+ var varsOnly_1 = ts.createMap();
+ members.forEach(function (p) {
+ if (!(p.flags & 418 /* BlockScoped */)) {
+ varsOnly_1.set(p.escapedName, p);
+ }
+ });
+ members = varsOnly_1;
+ }
}
setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
if (symbol.flags & 32 /* Class */) {
@@ -37631,7 +37958,7 @@
var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
- return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected);
+ return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
});
}
function getAllPossiblePropertiesOfTypes(types) {
@@ -37664,6 +37991,9 @@
return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
}
function getConstraintOfIndexedAccess(type) {
+ return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
+ }
+ function getConstraintFromIndexedAccess(type) {
var objectType = getConstraintOfType(type.objectType) || type.objectType;
if (objectType !== type.objectType) {
var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType);
@@ -37676,13 +38006,13 @@
}
function getDefaultConstraintOfConditionalType(type) {
if (!type.resolvedDefaultConstraint) {
- var rootTrueType = type.root.trueType;
- var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */)
- ? rootTrueType
- : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */
- ? rootTrueType.typeVariable
- : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]);
- type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]);
+ // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
+ // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
+ // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
+ // in effect treating `any` like `never` rather than `unknown` in this location.
+ var trueConstraint = getInferredTrueTypeFromConditionalType(type);
+ var falseConstraint = type.falseType;
+ type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
}
return type.resolvedDefaultConstraint;
}
@@ -37692,7 +38022,13 @@
// with its constraint. We do this because if the constraint is a union type it will be distributed
// over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
// removes 'undefined' from T.
- if (type.root.isDistributive) {
+ // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
+ // as the constraint for all type params (check type included) have been replace with `unknown`, which
+ // is going to produce even more false positive/negative results than the distribute constraint already does.
+ // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
+ // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
+ // likely doesn't need to exist.
+ if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
var simplified = getSimplifiedType(type.checkType);
var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
if (constraint && constraint !== type.checkType) {
@@ -37705,9 +38041,12 @@
}
return undefined;
}
- function getConstraintOfConditionalType(type) {
+ function getConstraintFromConditionalType(type) {
return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
}
+ function getConstraintOfConditionalType(type) {
+ return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
+ }
function getUnionConstraintOfIntersection(type, targetIsUnion) {
var constraints;
var hasDisjointDomainType = false;
@@ -37781,18 +38120,31 @@
if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
return circularConstraintType;
}
- if (constraintDepth === 50) {
+ if (constraintDepth >= 50) {
// We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
// very high likelyhood we're dealing with an infinite generic type that perpetually generates
// new type identities as we descend into it. We stop the recursion here and mark this type
// and the outer types as having circular constraints.
+ error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
nonTerminating = true;
return t.immediateBaseConstraint = noConstraintType;
}
constraintDepth++;
var result = computeBaseConstraint(getSimplifiedType(t));
constraintDepth--;
- if (!popTypeResolution() || nonTerminating) {
+ if (!popTypeResolution()) {
+ if (t.flags & 262144 /* TypeParameter */) {
+ var errorNode = getConstraintDeclaration(t);
+ if (errorNode) {
+ var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
+ if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
+ }
+ }
+ }
+ result = circularConstraintType;
+ }
+ if (nonTerminating) {
result = circularConstraintType;
}
t.immediateBaseConstraint = result || noConstraintType;
@@ -37834,8 +38186,11 @@
return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined;
}
if (t.flags & 16777216 /* Conditional */) {
- var constraint = getConstraintOfConditionalType(t);
- return constraint && getBaseConstraint(constraint);
+ var constraint = getConstraintFromConditionalType(t);
+ constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
+ var result = constraint && getBaseConstraint(constraint);
+ constraintDepth--;
+ return result;
}
if (t.flags & 33554432 /* Substitution */) {
return getBaseConstraint(t.substitute);
@@ -37896,7 +38251,7 @@
var typeVariable = getHomomorphicTypeVariable(type);
if (typeVariable) {
var constraint = getConstraintOfTypeParameter(typeVariable);
- if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) {
+ if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
var mapper = makeUnaryTypeMapper(typeVariable, constraint);
return instantiateType(type, combineTypeMappers(mapper, type.mapper));
}
@@ -37914,7 +38269,7 @@
t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
t.flags & 132 /* StringLike */ ? globalStringType :
t.flags & 296 /* NumberLike */ ? globalNumberType :
- t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) :
+ t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ESNext */) :
t.flags & 528 /* BooleanLike */ ? globalBooleanType :
t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
@@ -37922,7 +38277,7 @@
t;
}
function createUnionOrIntersectionProperty(containingType, name) {
- var props;
+ var propSet = ts.createMap();
var indexTypes;
var isUnion = containingType.flags & 1048576 /* Union */;
var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0;
@@ -37938,7 +38293,10 @@
var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
if (prop && !(modifiers & excludeModifiers)) {
commonFlags &= prop.flags;
- props = ts.appendIfUnique(props, prop);
+ var id = "" + getSymbolId(prop);
+ if (!propSet.has(id)) {
+ propSet.set(id, prop);
+ }
checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
(!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) |
(modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) |
@@ -37960,9 +38318,10 @@
}
}
}
- if (!props) {
+ if (!propSet.size) {
return undefined;
}
+ var props = ts.arrayFrom(propSet.values());
if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) {
return props[0];
}
@@ -38134,10 +38493,10 @@
function isJSDocOptionalParameter(node) {
return ts.isInJSFile(node) && (
// node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
- node.type && node.type.kind === 288 /* JSDocOptionalType */
+ node.type && node.type.kind === 293 /* JSDocOptionalType */
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -38171,7 +38530,7 @@
return false;
}
var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}
function createIdentifierTypePredicate(parameterName, parameterIndex, type) {
return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
@@ -38405,32 +38764,23 @@
}
}
signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
- createTypePredicateFromTypePredicateNode(type, signature.declaration) :
+ createTypePredicateFromTypePredicateNode(type, signature) :
jsdocPredicate || noTypePredicate;
}
ts.Debug.assert(!!signature.resolvedTypePredicate);
}
return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
}
- function createTypePredicateFromTypePredicateNode(node, func) {
+ function createTypePredicateFromTypePredicateNode(node, signature) {
var parameterName = node.parameterName;
var type = getTypeFromTypeNode(node.type);
if (parameterName.kind === 72 /* Identifier */) {
- return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type);
+ return createIdentifierTypePredicate(parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), 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 === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) {
- return i;
- }
- }
- return -1;
- }
function getReturnTypeOfSignature(signature) {
if (!signature.resolvedReturnType) {
if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
@@ -38502,8 +38852,19 @@
}
return undefined;
}
- function getSignatureInstantiation(signature, typeArguments, isJavascript) {
- return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ if (inferredTypeParameters) {
+ var returnSignature = getSingleCallSignature(getReturnTypeOfSignature(instantiatedSignature));
+ if (returnSignature) {
+ var newReturnSignature = cloneSignature(returnSignature);
+ newReturnSignature.typeParameters = inferredTypeParameters;
+ var newInstantiatedSignature = cloneSignature(instantiatedSignature);
+ newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
+ return newInstantiatedSignature;
+ }
+ }
+ return instantiatedSignature;
}
function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
@@ -38698,10 +39059,10 @@
for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
var type = types_5[_i];
if (!(type.flags & excludeKinds)) {
- result |= type.flags;
+ result |= ts.getObjectFlags(type);
}
}
- return result & 939524096 /* PropagatingFlags */;
+ return result & 917504 /* PropagatingFlags */;
}
function createTypeReference(target, typeArguments) {
var id = getTypeListId(typeArguments);
@@ -38709,7 +39070,7 @@
if (!type) {
type = createObjectType(4 /* Reference */, target.symbol);
target.instantiations.set(id, type);
- type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
+ type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
type.target = target;
type.typeArguments = typeArguments;
}
@@ -38875,7 +39236,7 @@
}
function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
- if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
+ if (symbol.valueDeclaration && symbol.valueDeclaration.parent && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
if (jsdocType) {
return jsdocType;
@@ -38896,6 +39257,9 @@
}
}
function getSubstitutionType(typeVariable, substitute) {
+ if (substitute.flags & 3 /* AnyOrUnknown */) {
+ return typeVariable;
+ }
var result = createType(33554432 /* Substitution */);
result.typeVariable = typeVariable;
result.substitute = substitute;
@@ -38911,7 +39275,7 @@
}
function getConstrainedTypeVariable(typeVariable, node) {
var constraints;
- while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) {
+ while (node && !ts.isStatement(node) && node.kind !== 296 /* JSDocComment */) {
var parent = node.parent;
if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) {
var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
@@ -39143,19 +39507,19 @@
function createIterableIteratorType(iteratedType) {
return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]);
}
- function createArrayType(elementType) {
- return createTypeFromGenericGlobalType(globalArrayType, [elementType]);
- }
- function createReadonlyArrayType(elementType) {
- return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]);
+ function createArrayType(elementType, readonly) {
+ return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
}
function getTypeFromArrayTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType));
+ links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType), isReadonlyTypeOperator(node.parent));
}
return links.resolvedType;
}
+ function isReadonlyTypeOperator(node) {
+ return ts.isTypeOperatorNode(node) && node.operator === 133 /* ReadonlyKeyword */;
+ }
// We represent tuple types as type references to synthesized generic interface types created by
// this function. The types are of the form:
//
@@ -39163,7 +39527,7 @@
//
// 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, minLength, hasRestElement, associatedNames) {
+ function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
var typeParameters;
var properties = [];
var maxLength = hasRestElement ? arity - 1 : arity;
@@ -39172,7 +39536,7 @@
for (var i = 0; i < arity; i++) {
var typeParameter = typeParameters[i] = createTypeParameter();
if (i < maxLength) {
- var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i);
+ var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
property.type = typeParameter;
properties.push(property);
}
@@ -39202,25 +39566,27 @@
type.declaredNumberIndexInfo = undefined;
type.minLength = minLength;
type.hasRestElement = hasRestElement;
+ type.readonly = readonly;
type.associatedNames = associatedNames;
return type;
}
- function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) {
- var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
+ function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
+ var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
var type = tupleTypes.get(key);
if (!type) {
- tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames));
+ tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames));
}
return type;
}
- function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) {
+ function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) {
if (minLength === void 0) { minLength = elementTypes.length; }
if (hasRestElement === void 0) { hasRestElement = false; }
+ if (readonly === void 0) { readonly = false; }
var arity = elementTypes.length;
if (arity === 1 && hasRestElement) {
- return createArrayType(elementTypes[0]);
+ return createArrayType(elementTypes[0], readonly);
}
- var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames);
+ var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames);
return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
}
function getTypeFromTupleTypeNode(node) {
@@ -39233,7 +39599,7 @@
var type = getTypeFromTypeNode(n);
return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type;
});
- links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1);
+ links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1, isReadonlyTypeOperator(node.parent));
}
return links.resolvedType;
}
@@ -39243,7 +39609,7 @@
// don't slice off rest element
index = Math.min(index, getTypeReferenceArity(type) - 1);
}
- return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index));
+ return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index));
}
function getTypeFromOptionalTypeNode(node) {
var type = getTypeFromTypeNode(node.type);
@@ -39301,12 +39667,14 @@
// intersections of unit types into 'never' upon construction, but deferring the reduction makes it
// easier to reason about their origin.
if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) {
- includes |= flags & ~939524096 /* ConstructionFlags */;
+ includes |= flags & 1835007 /* IncludesMask */;
+ if (flags & 66846720 /* StructuredOrInstantiable */)
+ includes |= 262144 /* IncludesStructuredOrInstantiable */;
if (type === wildcardType)
- includes |= 268435456 /* Wildcard */;
+ includes |= 4194304 /* IncludesWildcard */;
if (!strictNullChecks && flags & 98304 /* Nullable */) {
- if (!(flags & 134217728 /* ContainsWideningType */))
- includes |= 134217728 /* NonWideningType */;
+ if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */))
+ includes |= 2097152 /* IncludesNonWideningType */;
}
else {
var len = typeSet.length;
@@ -39327,17 +39695,6 @@
}
return includes;
}
- function isSubtypeOfAny(source, targets) {
- for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
- var target = targets_1[_i];
- if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
- !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
- isTypeDerivedFrom(source, target))) {
- return true;
- }
- }
- return false;
- }
function isSetOfLiteralsFromSameEnum(types) {
var first = types[0];
if (first.flags & 1024 /* EnumLiteral */) {
@@ -39352,18 +39709,43 @@
}
return false;
}
- function removeSubtypes(types) {
- if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) {
- return;
+ function removeSubtypes(types, primitivesOnly) {
+ var len = types.length;
+ if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
+ return true;
}
- var i = types.length;
+ var i = len;
+ var count = 0;
while (i > 0) {
i--;
- if (isSubtypeOfAny(types[i], types)) {
+ var source = types[i];
+ for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
+ var target = types_7[_i];
+ if (source !== target) {
+ if (count === 100000) {
+ // After 100000 subtype checks we estimate the remaining amount of work by assuming the
+ // same ratio of checks per element. If the estimated number of remaining type checks is
+ // greater than an upper limit we deem the union type too complex to represent. The
+ // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
+ // caps union types at 5000 unique literal types and 1000 unique object types.
+ var estimatedCount = (count / (len - i)) * len;
+ if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
+ error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
+ return false;
+ }
+ }
+ count++;
+ if (isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
+ !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
+ isTypeDerivedFrom(source, target))) {
ts.orderedRemoveItemAt(types, i);
+ break;
+ }
}
}
}
+ return true;
+ }
function removeRedundantLiteralTypes(types, includes) {
var i = types.length;
while (i > 0) {
@@ -39398,25 +39780,27 @@
var includes = addTypesToUnion(typeSet, 0, types);
if (unionReduction !== 0 /* None */) {
if (includes & 3 /* AnyOrUnknown */) {
- return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType;
+ return includes & 1 /* Any */ ? includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
}
switch (unionReduction) {
case 1 /* Literal */:
- if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) {
+ if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
removeRedundantLiteralTypes(typeSet, includes);
}
break;
case 2 /* Subtype */:
- removeSubtypes(typeSet);
+ if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
+ return errorType;
+ }
break;
}
if (typeSet.length === 0) {
- return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType :
- includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType :
+ return includes & 65536 /* Null */ ? includes & 2097152 /* IncludesNonWideningType */ ? nullType : nullWideningType :
+ includes & 32768 /* Undefined */ ? includes & 2097152 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
neverType;
}
}
- return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments);
+ return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments);
}
function getUnionTypePredicate(signatures) {
var first;
@@ -39453,7 +39837,7 @@
: !ts.isIdentifierTypePredicate(b);
}
// This function assumes the constituent type list is sorted and deduplicated.
- function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) {
+ function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
if (types.length === 0) {
return neverType;
}
@@ -39463,11 +39847,10 @@
var id = getTypeListId(types);
var type = unionTypes.get(id);
if (!type) {
- var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
- type = createType(1048576 /* Union */ | propagatedFlags);
+ type = createType(1048576 /* Union */);
unionTypes.set(id, type);
+ type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
type.types = types;
- type.primitiveTypesOnly = primitiveTypesOnly;
/*
Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
@@ -39493,16 +39876,16 @@
return addTypesToIntersection(typeSet, includes, type.types);
}
if (isEmptyAnonymousObjectType(type)) {
- if (!(includes & 536870912 /* EmptyObject */)) {
- includes |= 536870912 /* EmptyObject */;
+ if (!(includes & 8388608 /* IncludesEmptyObject */)) {
+ includes |= 8388608 /* IncludesEmptyObject */;
typeSet.push(type);
}
}
else {
- includes |= flags & ~939524096 /* ConstructionFlags */;
+ includes |= flags & 1835007 /* IncludesMask */;
if (flags & 3 /* AnyOrUnknown */) {
if (type === wildcardType)
- includes |= 268435456 /* Wildcard */;
+ includes |= 4194304 /* IncludesWildcard */;
}
else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) {
typeSet.push(type);
@@ -39513,8 +39896,8 @@
// Add the given types to the given type set. Order is preserved, freshness is removed from literal
// types, duplicates are removed, and nested types of the given kind are flattened into the set.
function addTypesToIntersection(typeSet, includes, types) {
- for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
- var type = types_7[_i];
+ for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
+ var type = types_8[_i];
includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
}
return includes;
@@ -39557,7 +39940,7 @@
// 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 & 1048576 /* Union */) && t.primitiveTypesOnly; });
+ var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); });
if (index < 0) {
return false;
}
@@ -39566,7 +39949,7 @@
// the unionTypes array.
while (i < types.length) {
var t = types[i];
- if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) {
+ if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) {
(unionTypes || (unionTypes = [types[index]])).push(t);
ts.orderedRemoveItemAt(types, i);
}
@@ -39595,7 +39978,7 @@
}
}
// Finally replace the first union with the result
- types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true);
+ types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */);
return true;
}
// We normalize combinations of intersection and union types based on the distributive property of the '&'
@@ -39615,7 +39998,7 @@
return neverType;
}
if (includes & 1 /* Any */) {
- return includes & 268435456 /* Wildcard */ ? wildcardType : anyType;
+ return includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType;
}
if (!strictNullChecks && includes & 98304 /* Nullable */) {
return includes & 32768 /* Undefined */ ? undefinedType : nullType;
@@ -39626,7 +40009,7 @@
includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
removeRedundantPrimitiveTypes(typeSet, includes);
}
- if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) {
+ if (includes & 8388608 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
}
if (typeSet.length === 0) {
@@ -39651,9 +40034,9 @@
var id = getTypeListId(typeSet);
var type = intersectionTypes.get(id);
if (!type) {
- var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */);
- type = createType(2097152 /* Intersection */ | propagatedFlags);
+ type = createType(2097152 /* Intersection */);
intersectionTypes.set(id, type);
+ type.objectFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */);
type.types = typeSet;
type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
type.aliasTypeArguments = aliasTypeArguments;
@@ -39708,7 +40091,7 @@
return neverType;
}
function getLiteralTypeFromProperties(type, include) {
- return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); }));
+ return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
}
function getNonEnumNumberIndexInfo(type) {
var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
@@ -39750,6 +40133,9 @@
? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
: errorType;
break;
+ case 133 /* ReadonlyKeyword */:
+ links.resolvedType = getTypeFromTypeNode(node.type);
+ break;
}
}
return links.resolvedType; // TODO: GH#18217
@@ -39852,7 +40238,10 @@
return anyType;
}
if (accessExpression && !isConstEnumObjectType(objectType)) {
- if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
+ if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
+ error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
+ }
+ else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
}
@@ -39904,7 +40293,7 @@
: accessNode;
}
function isGenericObjectType(type) {
- return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */);
+ return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 131072 /* GenericMappedType */);
}
function isGenericIndexType(type) {
return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */);
@@ -39950,12 +40339,15 @@
// that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
// construct the type Box<T[X]>.
if (isGenericMappedType(objectType)) {
- var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
- var templateMapper = combineTypeMappers(objectType.mapper, mapper);
- return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType);
+ return type.simplified = mapType(substituteIndexedMappedType(objectType, type.indexType), getSimplifiedType);
}
return type.simplified = type;
}
+ function substituteIndexedMappedType(objectType, index) {
+ var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
+ var templateMapper = combineTypeMappers(objectType.mapper, mapper);
+ return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
+ }
function getIndexedAccessType(objectType, indexType, accessNode, missingType) {
if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; }
if (objectType === wildcardType || indexType === wildcardType) {
@@ -40037,13 +40429,48 @@
function getActualTypeVariable(type) {
return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type;
}
+ /**
+ * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
+ */
+ function isIntersectionEmpty(type1, type2) {
+ return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
+ }
function getConditionalType(root, mapper) {
var checkType = instantiateType(root.checkType, mapper);
var extendsType = instantiateType(root.extendsType, mapper);
if (checkType === wildcardType || extendsType === wildcardType) {
return wildcardType;
}
- var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */);
+ var trueType = instantiateType(root.trueType, mapper);
+ var falseType = instantiateType(root.falseType, mapper);
+ var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType);
+ var result = conditionalTypes.get(instantiationId);
+ if (result) {
+ return result;
+ }
+ var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType);
+ conditionalTypes.set(instantiationId, newResult);
+ return newResult;
+ }
+ function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) {
+ // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
+ if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
+ if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
+ return trueType;
+ }
+ else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
+ return neverType;
+ }
+ }
+ else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
+ if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
+ return neverType;
+ }
+ else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
+ return falseType;
+ }
+ }
+ var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */);
var combinedMapper;
if (root.inferTypeParameters) {
var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
@@ -40053,25 +40480,25 @@
// types rules (i.e. proper contravariance) for inferences.
inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
}
- combinedMapper = combineTypeMappers(mapper, context);
+ combinedMapper = combineTypeMappers(mapper, context.mapper);
}
// Instantiate the extends type including inferences for 'infer T' type parameters
var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
// We attempt to resolve the conditional type only when the check and extends types are non-generic
- if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */)) {
+ if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */)) {
if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) {
- return instantiateType(root.trueType, mapper);
+ return trueType;
}
// Return union of trueType and falseType for 'any' since it matches anything
if (checkType.flags & 1 /* Any */) {
- return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]);
+ return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), falseType]);
}
- // Return falseType for a definitely false extends check. We check an instantations of the two
+ // Return falseType for a definitely false extends check. We check an instantiations of the two
// types with type parameters mapped to the wildcard type, the most permissive instantiations
// possible (the wildcard type is assignable to and from all types). If those are not related,
- // then no instatiations will be and we can just return the false branch type.
+ // then no instantiations will be and we can just return the false branch type.
if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) {
- return instantiateType(root.falseType, mapper);
+ return falseType;
}
// Return trueType for a definitely true extends check. We check instantiations of the two
// types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
@@ -40083,6 +40510,9 @@
}
}
// Return a deferred type for a check that is neither definitely true nor definitely false
+ return getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType);
+ }
+ function getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType) {
var erasedCheckType = getActualTypeVariable(checkType);
var result = createType(16777216 /* Conditional */);
result.root = root;
@@ -40090,15 +40520,14 @@
result.extendsType = extendsType;
result.mapper = mapper;
result.combinedMapper = combinedMapper;
+ result.trueType = trueType;
+ result.falseType = falseType;
result.aliasSymbol = root.aliasSymbol;
result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
return result;
}
- function getTrueTypeFromConditionalType(type) {
- return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
- }
- function getFalseTypeFromConditionalType(type) {
- return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
+ function getInferredTrueTypeFromConditionalType(type) {
+ return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper || type.mapper));
}
function getInferTypeParameters(node) {
var result;
@@ -40267,7 +40696,7 @@
* this function should be called in a left folding style, with left = previous result of getSpreadType
* and right = the new element to be spread.
*/
- function getSpreadType(left, right, symbol, typeFlags, objectFlags) {
+ function getSpreadType(left, right, symbol, objectFlags, readonly) {
if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
return anyType;
}
@@ -40281,10 +40710,10 @@
return left;
}
if (left.flags & 1048576 /* Union */) {
- return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); });
+ return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
}
if (right.flags & 1048576 /* Union */) {
- return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); });
+ return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
}
if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
return left;
@@ -40300,7 +40729,7 @@
var types = left.types;
var lastLeft = types[types.length - 1];
if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
- return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)]));
+ return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
}
}
return getIntersectionType([left, right]);
@@ -40324,7 +40753,7 @@
skippedPrivateMembers.set(rightProp.escapedName, true);
}
else if (isSpreadableProperty(rightProp)) {
- members.set(rightProp.escapedName, getSpreadSymbol(rightProp));
+ members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
}
}
for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
@@ -40348,12 +40777,11 @@
}
}
else {
- members.set(leftProp.escapedName, getSpreadSymbol(leftProp));
+ members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
}
}
- var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo));
- spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags;
- spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
+ var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
+ spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
return spread;
}
/** We approximate own properties as non-methods plus methods that are inside the object literal */
@@ -40361,25 +40789,21 @@
return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
!prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); });
}
- function getSpreadSymbol(prop) {
- var isReadonly = isReadonlySymbol(prop);
+ function getSpreadSymbol(prop, readonly) {
var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
- if (!isReadonly && !isSetonlyAccessor) {
+ if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
return prop;
}
var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
- var result = createSymbol(flags, prop.escapedName);
+ var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
result.declarations = prop.declarations;
result.nameType = prop.nameType;
result.syntheticOrigin = prop;
return result;
}
- function getNonReadonlyIndexSignature(index) {
- if (index && index.isReadonly) {
- return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration);
- }
- return index;
+ function getIndexInfoWithReadonly(info, readonly) {
+ return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
}
function createLiteralType(flags, value, symbol) {
var type = createType(flags);
@@ -40467,8 +40891,8 @@
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 120 /* AnyKeyword */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return anyType;
case 143 /* UnknownKeyword */:
return unknownType;
@@ -40515,23 +40939,23 @@
return getTypeFromUnionTypeNode(node);
case 174 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return getTypeFromJSDocNullableTypeNode(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return addOptionality(getTypeFromTypeNode(node.type));
case 177 /* ParenthesizedType */:
case 172 /* RestType */:
- case 287 /* JSDocNonNullableType */:
- case 283 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 288 /* JSDocTypeExpression */:
return getTypeFromTypeNode(node.type);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 297 /* JSDocTypeLiteral */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 179 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
@@ -40607,16 +41031,8 @@
* Maps forward-references to later types parameters to the empty object type.
* This is used during inference when instantiating type parameter defaults.
*/
- function createBackreferenceMapper(typeParameters, index) {
- return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; };
- }
- function isInferenceContext(mapper) {
- return !!mapper.typeParameters;
- }
- function cloneTypeMapper(mapper) {
- return mapper && isInferenceContext(mapper) ?
- createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) :
- mapper;
+ function createBackreferenceMapper(context, index) {
+ return function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? emptyObjectType : t; };
}
function combineTypeMappers(mapper1, mapper2) {
if (!mapper1)
@@ -40699,7 +41115,7 @@
}
// 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) & (2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */));
+ var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */));
result.declarations = symbol.declarations;
result.parent = symbol.parent;
result.target = symbol;
@@ -40795,7 +41211,7 @@
function getHomomorphicTypeVariable(type) {
var constraintType = getConstraintTypeFromMappedType(type);
if (constraintType.flags & 4194304 /* Index */) {
- var typeVariable = constraintType.type;
+ var typeVariable = getActualTypeVariable(constraintType.type);
if (typeVariable.flags & 262144 /* TypeParameter */) {
return typeVariable;
}
@@ -40817,30 +41233,27 @@
if (typeVariable) {
var mappedTypeVariable = instantiateType(typeVariable, mapper);
if (typeVariable !== mappedTypeVariable) {
- // If we are already in the process of creating an instantiation of this mapped type,
- // return the error type. This situation only arises if we are instantiating the mapped
- // type for an array or tuple type, as we then need to eagerly resolve the (possibly
- // circular) element type(s).
- if (type.instantiating) {
- return errorType;
- }
- type.instantiating = true;
- var result = mapType(mappedTypeVariable, function (t) {
- if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) {
+ return mapType(mappedTypeVariable, function (t) {
+ if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
var replacementMapper = createReplacementMapper(typeVariable, t, mapper);
- return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
- isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
+ return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
instantiateAnonymousType(type, replacementMapper);
}
return t;
});
- type.instantiating = false;
- return result;
}
}
return instantiateAnonymousType(type, mapper);
}
+ function getModifiedReadonlyState(state, modifiers) {
+ return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
+ }
+ function instantiateMappedArrayType(arrayType, mappedType, mapper) {
+ var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
+ return elementType === errorType ? errorType :
+ createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
+ }
function instantiateMappedTupleType(tupleType, mappedType, mapper) {
var minLength = tupleType.target.minLength;
var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) {
@@ -40850,7 +41263,9 @@
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);
+ var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
+ return ts.contains(elementTypes, errorType) ? errorType :
+ createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames);
}
function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key]));
@@ -40916,6 +41331,7 @@
// We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
// with a combination of infinite generic types that perpetually generate new type identities. We stop
// the recursion here by yielding the error type.
+ error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
return errorType;
}
instantiationDepth++;
@@ -40967,7 +41383,17 @@
return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
}
if (flags & 33554432 /* Substitution */) {
- return instantiateType(type.typeVariable, mapper);
+ var maybeVariable = instantiateType(type.typeVariable, mapper);
+ if (maybeVariable.flags & 8650752 /* TypeVariable */) {
+ return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
+ }
+ else {
+ var sub = instantiateType(type.substitute, mapper);
+ if (sub.flags & 3 /* AnyOrUnknown */ || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
+ return maybeVariable;
+ }
+ return sub;
+ }
}
return type;
}
@@ -40976,8 +41402,20 @@
type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
}
function getRestrictiveInstantiation(type) {
- return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
- type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper));
+ if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
+ return type;
+ }
+ if (type.restrictiveInstantiation) {
+ return type.restrictiveInstantiation;
+ }
+ type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
+ // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
+ // which is redundant - we'll produce new type identities, but all type params have already been mapped.
+ // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
+ // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
+ // are constrained to `unknown` and produce tons of false positives/negatives!
+ type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
+ return type.restrictiveInstantiation;
}
function instantiateIndexInfo(info, mapper) {
return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
@@ -41176,7 +41614,7 @@
var resultObj = {};
checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj);
var diagnostic = resultObj.error;
- addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
return true;
}
}
@@ -41211,7 +41649,7 @@
checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj);
if (resultObj.error) {
if (target.symbol && ts.length(target.symbol.declarations)) {
- addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
+ ts.addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
}
return true;
}
@@ -41258,13 +41696,13 @@
undefined;
if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
issuedElaboration = true;
- addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
+ ts.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))) {
var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
- addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
+ ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
}
}
}
@@ -41335,7 +41773,7 @@
// child is of the type of the expression
return { errorNode: child, innerExpression: child.expression, nameType: nameType };
case 11 /* JsxText */:
- if (child.containsOnlyWhiteSpaces) {
+ if (child.containsOnlyTriviaWhiteSpaces) {
break; // Whitespace only jsx text isn't real jsx text
}
// child is a string
@@ -41358,7 +41796,7 @@
var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
var childrenNameType = getLiteralType(childrenPropName);
var childrenTargetType = getIndexedAccessType(target, childrenNameType);
- var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyWhiteSpaces; });
+ var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
if (!ts.length(validChildren)) {
return result;
}
@@ -41446,7 +41884,7 @@
return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation);
}
// recreate a tuple from the elements, if possible
- var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true);
+ var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
if (isTupleLikeType(tupleizedType)) {
return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation);
}
@@ -41512,6 +41950,14 @@
/*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */;
}
/**
+ * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
+ */
+ function isAnySignature(s) {
+ return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
+ s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
+ isTypeAny(getReturnTypeOfSignature(s));
+ }
+ /**
* See signatureRelatedTo, compareSignaturesIdentical
*/
function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) {
@@ -41519,13 +41965,16 @@
if (source === target) {
return -1 /* True */;
}
+ if (isAnySignature(target)) {
+ return -1 /* True */;
+ }
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);
+ source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
}
var sourceCount = getParameterCount(source);
var sourceRestType = getNonArrayRestType(source);
@@ -41596,7 +42045,7 @@
if (targetTypePredicate) {
var sourceTypePredicate = getTypePredicateOfSignature(source);
if (sourceTypePredicate) {
- result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217
+ result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
}
else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
if (reportErrors) {
@@ -41615,7 +42064,7 @@
}
return result;
}
- function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) {
+ function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
if (source.kind !== target.kind) {
if (reportErrors) {
errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
@@ -41624,12 +42073,9 @@
return 0 /* False */;
}
if (source.kind === 1 /* Identifier */) {
- var targetPredicate = target;
- var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0);
- var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0);
- if (sourceIndex !== targetIndex) {
+ if (source.parameterIndex !== target.parameterIndex) {
if (reportErrors) {
- errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName);
+ errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
}
return 0 /* False */;
@@ -41830,7 +42276,7 @@
}
var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
if (relatedInfo) {
- addRelatedInfo.apply(void 0, [diag].concat(relatedInfo));
+ ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInfo));
}
if (errorOutputContainer) {
errorOutputContainer.error = diag;
@@ -42437,8 +42883,8 @@
if (source.root.isDistributive === target.root.isDistributive) {
if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
- if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
- if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
+ if (result_3 &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) {
+ if (result_3 &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) {
return result_3;
}
}
@@ -42453,6 +42899,7 @@
}
var result;
var originalErrorInfo;
+ var varianceCheckFailed = false;
var saveErrorInfo = errorInfo;
// We limit alias variance probing to only object and conditional types since their alias behavior
// is more predictable than other, interned types, which may or may not have an alias depending on
@@ -42461,11 +42908,10 @@
source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
!(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
var variances = getAliasVariances(source.aliasSymbol);
- if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) {
- return result;
+ var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances);
+ if (varianceResult !== undefined) {
+ return varianceResult;
}
- originalErrorInfo = errorInfo;
- errorInfo = saveErrorInfo;
}
if (target.flags & 262144 /* TypeParameter */) {
// A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q].
@@ -42522,9 +42968,18 @@
template.indexType === getTypeParameterFromMappedType(target)) {
return -1 /* True */;
}
+ if (!isGenericMappedType(source)) {
+ var targetConstraint = getConstraintTypeFromMappedType(target);
+ var sourceKeys_1 = getIndexType(source);
+ var hasOptionalUnionKeys = modifiers & 4 /* IncludeOptional */ && targetConstraint.flags & 1048576 /* Union */;
+ var filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, function (t) { return !!isRelatedTo(t, sourceKeys_1); }) : undefined;
// A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X.
- if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) {
- var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target));
+ // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X.
+ if (hasOptionalUnionKeys
+ ? !(filteredByApplicability.flags & 131072 /* Never */)
+ : isRelatedTo(targetConstraint, sourceKeys_1)) {
+ var indexingType = hasOptionalUnionKeys ? filteredByApplicability : getTypeParameterFromMappedType(target);
+ var indexedAccessType = getIndexedAccessType(source, indexingType);
var templateType = getTemplateTypeFromMappedType(target);
if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
return result;
@@ -42534,6 +42989,7 @@
errorInfo = saveErrorInfo;
}
}
+ }
if (source.flags & 8650752 /* TypeVariable */) {
if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
// A type S[K] is related to a type T[J] if S is related to T and K is related to J.
@@ -42577,8 +43033,8 @@
// and Y1 is related to Y2.
if (isTypeIdenticalTo(source.extendsType, target.extendsType) &&
(isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
- if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) {
- result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
+ if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) {
+ result &= isRelatedTo(source.falseType, target.falseType, reportErrors);
}
if (result) {
errorInfo = saveErrorInfo;
@@ -42627,36 +43083,19 @@
// type references (which are intended by be compared structurally). Obtain the variance
// information for the type parameters and relate the type arguments accordingly.
var variances = getVariances(source.target);
- if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) {
- return result;
- }
- // The type arguments did not relate appropriately, but it may be because we have no variance
- // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
- // arguments). It might also be the case that the target type has a 'void' type argument for
- // a covariant type parameter that is only used in return positions within the generic type
- // (in which case any type argument is permitted on the source side). In those cases we proceed
- // with a structural comparison. Otherwise, we know for certain the instantiations aren't
- // related and we can return here.
- if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) {
- // In some cases generic types that are covariant in regular type checking mode become
- // invariant in --strictFunctionTypes mode because one or more type parameters are used in
- // both co- and contravariant positions. In order to make it easier to diagnose *why* such
- // types are invariant, if any of the type parameters are invariant we reset the reported
- // errors and instead force a structural comparison (which will include elaborations that
- // reveal the reason).
- if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) {
- return 0 /* False */;
- }
- // We remember the original error information so we can restore it in case the structural
- // comparison unexpectedly succeeds. This can happen when the structural comparison result
- // is a Ternary.Maybe for example caused by the recursion depth limiter.
- originalErrorInfo = errorInfo;
- errorInfo = saveErrorInfo;
+ var varianceResult = relateVariances(source.typeArguments, target.typeArguments, variances);
+ if (varianceResult !== undefined) {
+ return varianceResult;
}
}
- else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) {
+ else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
}
+ // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
+ // and not `{} <- fresh({}) <- {[idx: string]: any}`
+ else if (relation === subtypeRelation && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
+ return 0 /* False */;
+ }
// Even if relationship doesn't hold for unions, intersections, or generic type references,
// it may hold in a structural comparison.
// In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
@@ -42678,17 +43117,57 @@
}
}
}
- if (result) {
- if (!originalErrorInfo) {
- errorInfo = saveErrorInfo;
+ if (varianceCheckFailed && result) {
+ errorInfo = originalErrorInfo || errorInfo || saveErrorInfo; // Use variance error (there is no structural one) and return false
+ }
+ else if (result) {
return result;
}
- errorInfo = originalErrorInfo;
}
}
+ return 0 /* False */;
+ function isNonGeneric(type) {
+ // If we're already in identity relationship checking, we should use `isRelatedTo`
+ // to catch the `Maybe` from an excessively deep type (which we then assume means
+ // that the type could possibly contain a generic)
+ if (relation === identityRelation) {
+ return isRelatedTo(type, getPermissiveInstantiation(type)) === -1 /* True */;
+ }
+ return isTypeIdenticalTo(type, getPermissiveInstantiation(type));
+ }
+ function relateVariances(sourceTypeArguments, targetTypeArguments, variances) {
+ if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors)) {
+ return result;
}
+ var allowStructuralFallback = (targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances)) || isNonGeneric(source) || isNonGeneric(target);
+ varianceCheckFailed = !allowStructuralFallback;
+ // The type arguments did not relate appropriately, but it may be because we have no variance
+ // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
+ // arguments). It might also be the case that the target type has a 'void' type argument for
+ // a covariant type parameter that is only used in return positions within the generic type
+ // (in which case any type argument is permitted on the source side). In those cases we proceed
+ // with a structural comparison. Otherwise, we know for certain the instantiations aren't
+ // related and we can return here.
+ if (variances !== ts.emptyArray && !allowStructuralFallback) {
+ // In some cases generic types that are covariant in regular type checking mode become
+ // invariant in --strictFunctionTypes mode because one or more type parameters are used in
+ // both co- and contravariant positions. In order to make it easier to diagnose *why* such
+ // types are invariant, if any of the type parameters are invariant we reset the reported
+ // errors and instead force a structural comparison (which will include elaborations that
+ // reveal the reason).
+ // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
+ // we can return `False` early here to skip calculating the structural error message we don't need.
+ if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) {
return 0 /* False */;
}
+ // We remember the original error information so we can restore it in case the structural
+ // comparison unexpectedly succeeds. This can happen when the structural comparison result
+ // is a Ternary.Maybe for example caused by the recursion depth limiter.
+ originalErrorInfo = errorInfo;
+ errorInfo = saveErrorInfo;
+ }
+ }
+ }
// A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
// related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
// that S and T are contra-variant whereas X and Y are co-variant.
@@ -43167,20 +43646,17 @@
return variances;
}
function getVariances(type) {
- if (!strictFunctionTypes) {
- return ts.emptyArray;
- }
- if (type === globalArrayType || type === globalReadonlyArrayType) {
- // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters)
+ // Arrays and tuples are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters)
+ if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
return ts.emptyArray;
}
return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
}
// Return true if the given type reference has a 'void' type argument for a covariant type parameter.
// See comment at call in recursiveTypeRelatedTo for when this case matters.
- function hasCovariantVoidArgument(type, variances) {
+ function hasCovariantVoidArgument(typeArguments, variances) {
for (var i = 0; i < variances.length; i++) {
- if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) {
+ if (variances[i] === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
return true;
}
}
@@ -43409,8 +43885,8 @@
}
function literalTypesWithSameBaseType(types) {
var commonBaseType;
- for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
- var t = types_8[_i];
+ for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
+ var t = types_9[_i];
var baseType = getBaseTypeOfLiteralType(t);
if (!commonBaseType) {
commonBaseType = baseType;
@@ -43443,7 +43919,7 @@
return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
}
function isArrayType(type) {
- return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType;
+ return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
}
function isReadonlyArrayType(type) {
return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
@@ -43454,8 +43930,7 @@
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<any>
- return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) ||
- !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
+ return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
}
function isEmptyArrayLiteralType(type) {
var elementType = isArrayType(type) ? type.typeArguments[0] : undefined;
@@ -43540,8 +44015,8 @@
}
function getFalsyFlagsOfTypes(types) {
var result = 0;
- for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
- var t = types_9[_i];
+ for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
+ var t = types_10[_i];
result |= getFalsyFlags(t);
}
return result;
@@ -43655,7 +44130,7 @@
var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
regularNew.flags = resolved.flags;
- regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */);
+ regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
type.regularType = regularNew;
return regularNew;
}
@@ -43734,14 +44209,14 @@
var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
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
+ result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening
return result;
}
function getWidenedType(type) {
return getWidenedTypeWithContext(type, /*context*/ undefined);
}
function getWidenedTypeWithContext(type, context) {
- if (type.flags & 402653184 /* RequiresWidening */) {
+ if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) {
if (type.flags & 98304 /* Nullable */) {
return anyType;
}
@@ -43778,7 +44253,7 @@
*/
function reportWideningErrorsInType(type) {
var errorReported = false;
- if (type.flags & 134217728 /* ContainsWideningType */) {
+ if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) {
if (type.flags & 1048576 /* Union */) {
if (ts.some(type.types, isEmptyObjectType)) {
errorReported = true;
@@ -43804,7 +44279,7 @@
for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
var p = _e[_d];
var t = getTypeOfSymbol(p);
- if (t.flags & 134217728 /* ContainsWideningType */) {
+ if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) {
if (!reportWideningErrorsInType(t)) {
error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
}
@@ -43850,7 +44325,7 @@
return;
}
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
return;
case 239 /* FunctionDeclaration */:
@@ -43877,14 +44352,14 @@
errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
}
function reportErrorsFromWidening(declaration, type) {
- if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) {
+ if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) {
// Report implicit any error within type if possible, otherwise report error on declaration
if (!reportWideningErrorsInType(type)) {
reportImplicitAny(declaration, type);
}
}
}
- function forEachMatchingParameterType(source, target, callback) {
+ function applyToParameterTypes(source, target, callback) {
var sourceCount = getParameterCount(source);
var targetCount = getParameterCount(target);
var sourceRestType = getEffectiveRestType(source);
@@ -43905,25 +44380,55 @@
callback(getRestTypeAtPosition(source, paramCount), targetRestType);
}
}
- function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) {
- var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo);
- var context = mapper;
- context.typeParameters = typeParameters;
- context.signature = signature;
- context.inferences = inferences;
- context.flags = flags;
- context.compareTypes = compareTypes || compareTypesAssignable;
+ function applyToReturnTypes(source, target, callback) {
+ var sourceTypePredicate = getTypePredicateOfSignature(source);
+ var targetTypePredicate = getTypePredicateOfSignature(target);
+ if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind &&
+ (sourceTypePredicate.kind === 0 /* This */ || sourceTypePredicate.parameterIndex === targetTypePredicate.parameterIndex)) {
+ callback(sourceTypePredicate.type, targetTypePredicate.type);
+ }
+ else {
+ callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
+ }
+ }
+ function createInferenceContext(typeParameters, signature, flags, compareTypes) {
+ return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
+ }
+ function cloneInferenceContext(context, extraFlags) {
+ if (extraFlags === void 0) { extraFlags = 0; }
+ return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
+ }
+ function cloneInferredPartOfContext(context) {
+ var inferences = ts.filter(context.inferences, hasInferenceCandidates);
+ return inferences.length ?
+ createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
+ undefined;
+ }
+ function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
+ var context = {
+ inferences: inferences,
+ signature: signature,
+ flags: flags,
+ compareTypes: compareTypes,
+ mapper: function (t) { return mapToInferredType(context, t, /*fix*/ true); },
+ nonFixingMapper: function (t) { return mapToInferredType(context, t, /*fix*/ false); },
+ };
return context;
- function mapper(t) {
+ }
+ function mapToInferredType(context, t, fix) {
+ var inferences = context.inferences;
for (var i = 0; i < inferences.length; i++) {
- if (t === inferences[i].typeParameter) {
- inferences[i].isFixed = true;
+ var inference = inferences[i];
+ if (t === inference.typeParameter) {
+ if (fix && !inference.isFixed) {
+ inference.isFixed = true;
+ inference.inferredType = undefined;
+ }
return getInferredType(context, i);
}
}
return t;
}
- }
function createInferenceInfo(typeParameter) {
return {
typeParameter: typeParameter,
@@ -43946,6 +44451,9 @@
isFixed: inference.isFixed
};
}
+ function getMapperFromContext(context) {
+ return context && context.mapper;
+ }
// Return true if the given type could possibly reference a type parameter for which
// we perform type inference (i.e. a type parameter of a generic function). We cache
// results for union and intersection types for performance reasons.
@@ -44002,31 +44510,21 @@
return type;
}
function createReverseMappedType(source, target, constraint) {
- var properties = getPropertiesOfType(source);
- if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) {
- return undefined;
- }
// If any property contains context sensitive functions that have been skipped, the source type
// is incomplete and we can't infer a meaningful input type.
- for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
- var prop = properties_3[_i];
- if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) {
+ if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || getPropertiesOfType(source).length === 0 && !getIndexInfoOfType(source, 0 /* String */)) {
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, constraint));
- }
- if (isReadonlyArrayType(source)) {
- return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint));
+ return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint), isReadonlyArrayType(source));
}
if (isTupleType(source)) {
var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); });
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);
+ return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, 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.
@@ -44047,16 +44545,16 @@
return getTypeFromInference(inference);
}
function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
- var properties, _i, properties_4, targetProp, sourceProp, targetType, sourceType;
+ var properties, _i, properties_3, targetProp, sourceProp, targetType, sourceType;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target);
- _i = 0, properties_4 = properties;
+ _i = 0, properties_3 = properties;
_a.label = 1;
case 1:
- if (!(_i < properties_4.length)) return [3 /*break*/, 6];
- targetProp = properties_4[_i];
+ if (!(_i < properties_3.length)) return [3 /*break*/, 6];
+ targetProp = properties_3[_i];
if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 5];
sourceProp = getPropertyOfType(source, targetProp.escapedName);
if (!!sourceProp) return [3 /*break*/, 3];
@@ -44100,11 +44598,11 @@
inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
emptyObjectType;
}
- function inferTypes(inferences, originalSource, originalTarget, priority) {
+ function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
if (priority === void 0) { priority = 0; }
+ if (contravariant === void 0) { contravariant = false; }
var symbolStack;
var visited;
- var contravariant = false;
var bivariant = false;
var propagationType;
var allowComplexConstraintInference = true;
@@ -44180,7 +44678,7 @@
// not contain anyFunctionType when we come back to this argument for its second round
// of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
// when constructing types from type parameters that had no inference candidates).
- if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) {
+ if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) {
return;
}
var inference = getInferenceInfoForType(target);
@@ -44189,6 +44687,7 @@
if (inference.priority === undefined || priority < inference.priority) {
inference.candidates = undefined;
inference.contraCandidates = undefined;
+ inference.topLevel = true;
inference.priority = priority;
}
if (priority === inference.priority) {
@@ -44196,14 +44695,19 @@
// We make contravariant inferences only if we are in a pure contravariant position,
// i.e. only if we have not descended into a bivariant position.
if (contravariant && !bivariant) {
- inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate);
+ if (!ts.contains(inference.contraCandidates, candidate)) {
+ inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
+ inference.inferredType = undefined;
}
- else {
- inference.candidates = ts.appendIfUnique(inference.candidates, candidate);
+ }
+ else if (!ts.contains(inference.candidates, candidate)) {
+ inference.candidates = ts.append(inference.candidates, candidate);
+ inference.inferredType = undefined;
}
}
- if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) {
+ if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
inference.topLevel = false;
+ inference.inferredType = undefined;
}
}
return;
@@ -44227,6 +44731,9 @@
}
}
}
+ else if (target.flags & 33554432 /* Substitution */) {
+ inferFromTypes(source, target.typeVariable);
+ }
if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) {
// If source and target are references to the same generic type, infer from type arguments
var sourceTypes = source.typeArguments || ts.emptyArray;
@@ -44263,42 +44770,48 @@
else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) {
inferFromTypes(source.checkType, target.checkType);
inferFromTypes(source.extendsType, target.extendsType);
- inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
- inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
+ inferFromTypes(source.trueType, target.trueType);
+ inferFromTypes(source.falseType, target.falseType);
}
- else if (target.flags & 16777216 /* Conditional */) {
- inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]));
+ else if (target.flags & 16777216 /* Conditional */ && !contravariant) {
+ inferFromTypes(source, target.trueType);
+ inferFromTypes(source, target.falseType);
}
else if (target.flags & 3145728 /* UnionOrIntersection */) {
- var targetTypes = target.types;
+ // We infer from types that are not naked type variables first so that inferences we
+ // make from nested naked type variables and given slightly higher priority by virtue
+ // of being first in the candidates array.
var typeVariableCount = 0;
- var typeVariable = void 0;
- // First infer to each type in union or intersection that isn't a type variable
- for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) {
- var t = targetTypes_3[_d];
+ for (var _d = 0, _e = target.types; _d < _e.length; _d++) {
+ var t = _e[_d];
if (getInferenceInfoForType(t)) {
- typeVariable = t;
typeVariableCount++;
}
else {
inferFromTypes(source, t);
}
}
- // Next, if target containings a single naked type variable, make a secondary inference to that type
- // variable. This gives meaningful results for union types in co-variant positions and intersection
- // types in contra-variant positions (such as callback parameters).
- if (typeVariableCount === 1) {
+ // Inferences directly to naked type variables are given lower priority as they are
+ // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
+ // we want to infer string for T, not Promise<string> | string. For intersection types
+ // we only infer to single naked type variables.
+ if (target.flags & 1048576 /* Union */ ? typeVariableCount !== 0 : typeVariableCount === 1) {
var savePriority = priority;
priority |= 1 /* NakedTypeVariable */;
- inferFromTypes(source, typeVariable);
+ for (var _f = 0, _g = target.types; _f < _g.length; _f++) {
+ var t = _g[_f];
+ if (getInferenceInfoForType(t)) {
+ inferFromTypes(source, t);
+ }
+ }
priority = savePriority;
}
}
else if (source.flags & 1048576 /* Union */) {
// Source is a union or intersection type, infer from each constituent type
var sourceTypes = source.types;
- for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) {
- var sourceType = sourceTypes_3[_e];
+ for (var _h = 0, sourceTypes_3 = sourceTypes; _h < sourceTypes_3.length; _h++) {
+ var sourceType = sourceTypes_3[_h];
inferFromTypes(sourceType, target);
}
}
@@ -44314,7 +44827,7 @@
// that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
// here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
// (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
- // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just
+ // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
// remove this `allowComplexConstraintInference` flag.
allowComplexConstraintInference = false;
return inferFromTypes(apparentSource, target);
@@ -44376,12 +44889,12 @@
}
return undefined;
}
- function inferFromMappedTypeConstraint(source, target, constraintType) {
+ function inferToMappedType(source, target, constraintType) {
if (constraintType.flags & 1048576 /* Union */) {
var result = false;
for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
var type = _a[_i];
- result = inferFromMappedTypeConstraint(source, target, type) || result;
+ result = inferToMappedType(source, target, type) || result;
}
return result;
}
@@ -44403,12 +44916,22 @@
return true;
}
if (constraintType.flags & 262144 /* TypeParameter */) {
- // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type
- // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X.
+ // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
+ // parameter. First infer from 'keyof S' to K.
var savePriority = priority;
priority |= 4 /* MappedTypeConstraint */;
inferFromTypes(getIndexType(source), constraintType);
priority = savePriority;
+ // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
+ // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
+ // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
+ // Pick<T, K>.
+ var extendedConstraint = getConstraintOfType(constraintType);
+ if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
+ return true;
+ }
+ // If no inferences can be made to K's constraint, infer from a union of the property types
+ // in the source to the template type X.
var valueTypes = ts.compact([
getIndexTypeOfType(source, 0 /* String */),
getIndexTypeOfType(source, 1 /* Number */)
@@ -44427,7 +44950,7 @@
}
if (ts.getObjectFlags(target) & 32 /* Mapped */) {
var constraintType = getConstraintTypeFromMappedType(target);
- if (inferFromMappedTypeConstraint(source, target, constraintType)) {
+ if (inferToMappedType(source, target, constraintType)) {
return;
}
}
@@ -44440,11 +44963,11 @@
}
}
function inferFromProperties(source, target) {
- if (isTupleType(source)) {
+ if (isArrayType(source) || isTupleType(source)) {
if (isTupleType(target)) {
- var sourceLength = getLengthOfTupleType(source);
+ var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0;
var targetLength = getLengthOfTupleType(target);
- var sourceRestType = getRestTypeOfTupleType(source);
+ var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source);
var targetRestType = getRestTypeOfTupleType(target);
var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
for (var i = 0; i < fixedLength; i++) {
@@ -44467,8 +44990,8 @@
}
}
var properties = getPropertiesOfObjectType(target);
- for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
- var targetProp = properties_5[_i];
+ for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) {
+ var targetProp = properties_4[_i];
var sourceProp = getPropertyOfType(source, targetProp.escapedName);
if (sourceProp) {
inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
@@ -44481,7 +45004,7 @@
var sourceLen = sourceSignatures.length;
var targetLen = targetSignatures.length;
var len = sourceLen < targetLen ? sourceLen : targetLen;
- var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */);
+ var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */);
for (var i = 0; i < len; i++) {
inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters);
}
@@ -44492,17 +45015,10 @@
var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
// Once we descend into a bivariant signature we remain bivariant for all nested inferences
bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */;
- forEachMatchingParameterType(source, target, inferFromContravariantTypes);
+ applyToParameterTypes(source, target, inferFromContravariantTypes);
bivariant = saveBivariant;
}
- var sourceTypePredicate = getTypePredicateOfSignature(source);
- var targetTypePredicate = getTypePredicateOfSignature(target);
- if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) {
- inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type);
- }
- else {
- inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
- }
+ applyToReturnTypes(source, target, inferFromTypes);
}
function inferFromIndexTypes(source, target) {
var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
@@ -44525,8 +45041,8 @@
}
}
function typeIdenticalToSomeType(type, types) {
- for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
- var t = types_10[_i];
+ for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
+ var t = types_11[_i];
if (isTypeIdenticalTo(t, type)) {
return true;
}
@@ -44619,7 +45135,7 @@
if (defaultType) {
// Instantiate the default type. Any forward reference to a type
// parameter should be instantiated to the empty object type.
- inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
}
else {
inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
@@ -44632,7 +45148,7 @@
inference.inferredType = inferredType;
var constraint = getConstraintOfTypeParameter(inference.typeParameter);
if (constraint) {
- var instantiatedConstraint = instantiateType(constraint, context);
+ var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
inference.inferredType = inferredType = instantiatedConstraint;
}
@@ -44657,17 +45173,23 @@
case "console":
return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
case "$":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
case "describe":
case "suite":
case "it":
case "test":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha;
case "process":
case "require":
case "Buffer":
case "module":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
case "Map":
case "Set":
case "Promise":
@@ -44803,9 +45325,8 @@
}
return false;
}
- function hasNarrowableDeclaredType(expr) {
- var type = getDeclaredTypeOfReference(expr);
- return !!(type && type.flags & 1048576 /* Union */);
+ function isSyntheticThisPropertyAccess(expr) {
+ return ts.isAccessExpression(expr) && expr.expression.kind === 100 /* ThisKeyword */ && !!(expr.expression.flags & 8 /* Synthesized */);
}
function findDiscriminantProperties(sourceProperties, target) {
var result;
@@ -44882,8 +45403,8 @@
}
function getTypeFactsOfTypes(types) {
var result = 0 /* None */;
- for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
- var t = types_11[_i];
+ for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
+ var t = types_12[_i];
result |= getTypeFacts(t);
}
return result;
@@ -45163,7 +45684,7 @@
if (type.flags & 1048576 /* Union */) {
var types = type.types;
var filtered = ts.filter(types, f);
- return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly);
+ return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
}
return f(type) ? type : neverType;
}
@@ -45177,8 +45698,8 @@
var types = type.types;
var mappedType;
var mappedTypes;
- for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
- var current = types_12[_i];
+ for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
+ var current = types_13[_i];
var t = mapper(current);
if (t) {
if (!mappedType) {
@@ -45260,8 +45781,8 @@
}
function isEvolvingArrayTypeList(types) {
var hasEvolvingArrayType = false;
- for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
- var t = types_13[_i];
+ for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
+ var t = types_14[_i];
if (!(t.flags & 131072 /* Never */)) {
if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
return false;
@@ -45759,6 +46280,15 @@
assumeTrue = !assumeTrue;
}
var valueType = getTypeOfExpression(value);
+ if ((type.flags & 2 /* Unknown */) && (operator === 35 /* EqualsEqualsEqualsToken */) && assumeTrue) {
+ if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
+ return valueType;
+ }
+ if (valueType.flags & 524288 /* Object */) {
+ return nonPrimitiveType;
+ }
+ return type;
+ }
if (valueType.flags & 98304 /* Nullable */) {
if (!strictNullChecks) {
return type;
@@ -45788,9 +46318,9 @@
// We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands
var target = getReferenceCandidate(typeOfExpr.expression);
if (!isMatchingReference(reference, target)) {
- // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a
- // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type.
- if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) {
+ // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the
+ // narrowed type of 'y' to its declared type.
+ if (containsMatchingReference(reference, target)) {
return declaredType;
}
return type;
@@ -45831,13 +46361,37 @@
}
}
function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
- // We only narrow if all case expressions specify values with unit types
+ // We only narrow if all case expressions specify
+ // values with unit types, except for the case where
+ // `type` is unknown. In this instance we map object
+ // types to the nonPrimitive type and narrow with that.
var switchTypes = getSwitchClauseTypes(switchStatement);
if (!switchTypes.length) {
return type;
}
var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
+ if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
+ var groundClauseTypes = void 0;
+ for (var i = 0; i < clauseTypes.length; i += 1) {
+ var t = clauseTypes[i];
+ if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
+ if (groundClauseTypes !== undefined) {
+ groundClauseTypes.push(t);
+ }
+ }
+ else if (t.flags & 524288 /* Object */) {
+ if (groundClauseTypes === undefined) {
+ groundClauseTypes = clauseTypes.slice(0, i);
+ }
+ groundClauseTypes.push(nonPrimitiveType);
+ }
+ else {
+ return type;
+ }
+ }
+ return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
+ }
var discriminantType = getUnionType(clauseTypes);
var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
@@ -45938,9 +46492,14 @@
function narrowTypeByInstanceof(type, expr, assumeTrue) {
var left = getReferenceCandidate(expr.left);
if (!isMatchingReference(reference, left)) {
- // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an
- // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type.
- if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) {
+ // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the
+ // narrowed type of 'y' to its declared type. We do this because preceding 'x.y'
+ // references might reference a different 'y' property. However, we make an exception
+ // for property accesses where x is a synthetic 'this' expression, indicating that we
+ // were called from isPropertyInitializedInConstructor. Without this exception,
+ // initializations of 'this' properties that occur before a 'this instanceof XXX'
+ // check would not be considered.
+ if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) {
return declaredType;
}
return type;
@@ -46007,7 +46566,7 @@
return type;
}
if (ts.isIdentifierTypePredicate(predicate)) {
- var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)];
+ var predicateArgument = callExpression.arguments[predicate.parameterIndex];
if (predicateArgument) {
if (isMatchingReference(reference, predicateArgument)) {
return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
@@ -46084,7 +46643,7 @@
return ts.findAncestor(node.parent, function (node) {
return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
node.kind === 245 /* ModuleBlock */ ||
- node.kind === 279 /* SourceFile */ ||
+ node.kind === 284 /* SourceFile */ ||
node.kind === 154 /* PropertyDeclaration */;
});
}
@@ -46205,7 +46764,7 @@
// 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 !== 279 /* SourceFile */) {
+ while (container.kind !== 284 /* SourceFile */) {
if (container.parent === declaration) {
if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
@@ -46311,6 +46870,7 @@
function checkNestedBlockScopedBinding(node, symbol) {
if (languageVersion >= 2 /* ES2015 */ ||
(symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
+ ts.isSourceFile(symbol.valueDeclaration) ||
symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) {
return;
}
@@ -46498,22 +47058,27 @@
if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
captureLexicalThis(node, container);
}
- var type = tryGetThisTypeAt(node, container);
- if (!type && noImplicitThis) {
+ var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
+ if (noImplicitThis) {
+ var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
+ if (type === globalThisType_1 && capturedByArrowFunction) {
+ error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
+ }
+ else if (!type) {
// With noImplicitThis, functions may not reference 'this' if it has type 'any'
- var diag = error(node, capturedByArrowFunction && container.kind === 279 /* 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);
+ var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
if (!ts.isSourceFile(container)) {
var outsideThis = tryGetThisTypeAt(container);
- if (outsideThis) {
- addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
+ if (outsideThis && outsideThis !== globalThisType_1) {
+ ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
+ }
}
}
}
return type || anyType;
}
- function tryGetThisTypeAt(node, container) {
+ function tryGetThisTypeAt(node, includeGlobalThis, container) {
+ if (includeGlobalThis === void 0) { includeGlobalThis = true; }
if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
var isInJS = ts.isInJSFile(node);
if (ts.isFunctionLike(container) &&
@@ -46558,6 +47123,16 @@
return getFlowTypeOfReference(node, type);
}
}
+ if (ts.isSourceFile(container)) {
+ // look up in the source file's locals or exports
+ if (container.commonJsModuleIndicator) {
+ var fileSymbol = getSymbolOfNode(container);
+ return fileSymbol && getTypeOfSymbol(fileSymbol);
+ }
+ else if (includeGlobalThis) {
+ return getTypeOfSymbol(globalThisSymbol);
+ }
+ }
}
function getClassNameFromPrototypeMethod(container) {
// Check if it's the RHS of a x.prototype.y = function [name]() { .... }
@@ -46613,7 +47188,7 @@
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 294 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -46627,7 +47202,7 @@
}
}
function isInConstructorArgumentInitializer(node, constructorDecl) {
- return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; });
+ return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 151 /* Parameter */ && n.parent === constructorDecl; });
}
function checkSuperExpression(node) {
var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node;
@@ -46852,7 +47427,7 @@
while (type) {
var thisType = getThisTypeFromContextualType(type);
if (thisType) {
- return instantiateType(thisType, getContextualMapper(containingLiteral));
+ return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
}
if (literal.parent.kind !== 275 /* PropertyAssignment */) {
break;
@@ -47147,7 +47722,15 @@
}
function getTypeOfPropertyOfContextualType(type, name) {
return mapType(type, function (t) {
- if (t.flags & 3670016 /* StructuredType */) {
+ if (isGenericMappedType(t)) {
+ var constraint = getConstraintTypeFromMappedType(t);
+ var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
+ var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
+ if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
+ return substituteIndexedMappedType(t, propertyNameType);
+ }
+ }
+ else if (t.flags & 3670016 /* StructuredType */) {
var prop = getPropertyOfType(t, name);
if (prop) {
return getTypeOfSymbol(prop);
@@ -47283,18 +47866,46 @@
// Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
// be "pushed" onto a node using the contextualType property.
function getApparentTypeOfContextualType(node) {
- var contextualType = getContextualType(node);
- contextualType = contextualType && mapType(contextualType, getApparentType);
- if (contextualType && contextualType.flags & 1048576 /* Union */) {
+ var contextualType = instantiateContextualType(getContextualType(node), node);
+ if (contextualType) {
+ var apparentType = mapType(contextualType, getApparentType, /*noReductions*/ true);
+ if (apparentType.flags & 1048576 /* Union */) {
if (ts.isObjectLiteralExpression(node)) {
- return discriminateContextualTypeByObjectMembers(node, contextualType);
+ return discriminateContextualTypeByObjectMembers(node, apparentType);
}
else if (ts.isJsxAttributes(node)) {
- return discriminateContextualTypeByJSXAttributes(node, contextualType);
+ return discriminateContextualTypeByJSXAttributes(node, apparentType);
+ }
+ }
+ return apparentType;
+ }
+ }
+ // If the given contextual type contains instantiable types and if a mapper representing
+ // return type inferences is available, instantiate those types using that mapper.
+ function instantiateContextualType(contextualType, node) {
+ if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) {
+ var inferenceContext = getInferenceContext(node);
+ if (inferenceContext && inferenceContext.returnMapper) {
+ return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
}
}
return contextualType;
}
+ // This function is similar to instantiateType, except that (a) it only instantiates types that
+ // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
+ // no reductions on instantiated union types.
+ function instantiateInstantiableTypes(type, mapper) {
+ if (type.flags & 63176704 /* Instantiable */) {
+ return instantiateType(type, mapper);
+ }
+ if (type.flags & 1048576 /* Union */) {
+ return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
+ }
+ if (type.flags & 2097152 /* Intersection */) {
+ return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
+ }
+ return type;
+ }
/**
* Woah! Do you really want to use this function?
*
@@ -47340,7 +47951,7 @@
return getContextualTypeForArgument(parent, node);
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- return getTypeFromTypeNode(parent.type);
+ return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type);
case 204 /* BinaryExpression */:
return getContextualTypeForBinaryOperand(node);
case 275 /* PropertyAssignment */:
@@ -47374,9 +47985,9 @@
}
return undefined;
}
- function getContextualMapper(node) {
- var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; });
- return ancestor ? ancestor.contextualMapper : identityMapper;
+ function getInferenceContext(node) {
+ var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
+ return ancestor && ancestor.inferenceContext;
}
function getContextualJsxElementAttributesType(node) {
if (ts.isJsxOpeningElement(node) && node.parent.contextualType) {
@@ -47557,8 +48168,8 @@
}
var signatureList;
var types = type.types;
- for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
- var current = types_14[_i];
+ for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
+ var current = types_15[_i];
var signature = getContextualCallSignature(current, node);
if (signature) {
if (!signatureList) {
@@ -47576,12 +48187,7 @@
}
}
// Result is union of signatures collected (return type is union of return types of this signature set)
- var result;
- if (signatureList) {
- result = cloneSignature(signatureList[0]);
- result.unionSignatures = signatureList;
- }
- return result;
+ return signatureList && createUnionSignature(signatureList[0], signatureList);
}
function checkSpreadExpression(node, checkMode) {
if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
@@ -47601,6 +48207,7 @@
var elementTypes = [];
var inDestructuringPattern = ts.isAssignmentTarget(node);
var contextualType = getApparentTypeOfContextualType(node);
+ var inConstContext = isConstContext(node);
for (var index = 0; index < elementCount; index++) {
var e = elements[index];
if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) {
@@ -47643,21 +48250,24 @@
type.pattern = node;
return type;
}
- else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) {
+ else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, inConstContext)) {
return tupleResult;
}
else if (forceTuple) {
return createTupleType(elementTypes, minLength, hasRestElement);
}
}
- return getArrayLiteralType(elementTypes, 2 /* Subtype */);
+ return createArrayType(elementTypes.length ?
+ getUnionType(elementTypes, 2 /* Subtype */) :
+ strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext);
}
- function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) {
+ function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) {
if (elementCount === void 0) { elementCount = elementTypes.length; }
+ if (readonly === void 0) { readonly = false; }
// Infer a tuple type when the contextual type is or contains a tuple-like type
- if (contextualType && forEachType(contextualType, isTupleLikeType)) {
+ if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) {
var minLength = elementCount - (hasRestElement ? 1 : 0);
- var pattern = contextualType.pattern;
+ var pattern = contextualType && 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 (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) {
@@ -47675,14 +48285,8 @@
}
}
}
- return createTupleType(elementTypes, minLength, hasRestElement);
- }
+ return createTupleType(elementTypes, minLength, hasRestElement, readonly);
}
- function getArrayLiteralType(elementTypes, unionReduction) {
- if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
- return createArrayType(elementTypes.length ?
- getUnionType(elementTypes, unionReduction) :
- strictNullChecks ? implicitNeverType : undefinedWideningType);
}
function isNumericName(name) {
switch (name.kind) {
@@ -47746,15 +48350,15 @@
}
return links.resolvedType;
}
- function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) {
+ function getObjectLiteralIndexInfo(node, offset, properties, kind) {
var propTypes = [];
for (var i = 0; i < properties.length; i++) {
- if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) {
+ if (kind === 0 /* String */ || isNumericName(node.properties[i + offset].name)) {
propTypes.push(getTypeOfSymbol(properties[i]));
}
}
var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
- return createIndexInfo(unionType, /*isReadonly*/ false);
+ return createIndexInfo(unionType, isConstContext(node));
}
function getImmediateAliasedSymbol(symbol) {
ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
@@ -47774,14 +48378,15 @@
var propertiesTable;
var propertiesArray = [];
var spread = emptyObjectType;
- var propagatedFlags = 0;
var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */);
+ var inConstContext = isConstContext(node);
+ var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
var enumTag = ts.getJSDocEnumTag(node);
var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
- var typeFlags = 0;
+ var objectFlags = freshObjectLiteralFlag;
var patternWithComputedProperties = false;
var hasComputedStringProperty = false;
var hasComputedNumberProperty = false;
@@ -47808,11 +48413,11 @@
checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
}
}
- typeFlags |= type.flags;
+ objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */;
var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
var prop = nameType ?
- createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), 2048 /* Late */) :
- createSymbol(4 /* Property */ | member.flags, member.escapedName);
+ createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 2048 /* Late */) :
+ createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
if (nameType) {
prop.nameType = nameType;
}
@@ -47850,19 +48455,18 @@
checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
}
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
propertiesArray = [];
propertiesTable = ts.createSymbolTable();
hasComputedStringProperty = false;
hasComputedNumberProperty = false;
- typeFlags = 0;
}
var type = checkExpression(memberDecl.expression);
if (!isValidSpreadType(type)) {
error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
return errorType;
}
- spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
offset = i + 1;
continue;
}
@@ -47909,17 +48513,16 @@
}
if (spread !== emptyObjectType) {
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
}
return spread;
}
return createObjectLiteralType();
function createObjectLiteralType() {
- var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined;
- var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined;
+ var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
+ var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
- result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */;
- result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag;
+ result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
if (isJSObjectLiteral) {
result.objectFlags |= 16384 /* JSLiteral */;
}
@@ -47929,7 +48532,6 @@
if (inDestructuringPattern) {
result.pattern = node;
}
- propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */;
return result;
}
}
@@ -48005,7 +48607,6 @@
var hasSpreadAnyType = false;
var typeToIntersect;
var explicitlySpecifyChildrenAttribute = false;
- var typeFlags = 0;
var objectFlags = 4096 /* JsxAttributes */;
var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
@@ -48013,7 +48614,7 @@
var member = attributeDecl.symbol;
if (ts.isJsxAttribute(attributeDecl)) {
var exprType = checkJsxAttribute(attributeDecl, checkMode);
- typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */;
+ objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */;
var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
attributeSymbol.declarations = member.declarations;
attributeSymbol.parent = member.parent;
@@ -48030,7 +48631,7 @@
else {
ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */);
if (attributesTable.size > 0) {
- spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
attributesTable = ts.createSymbolTable();
}
var exprType = checkExpressionCached(attributeDecl.expression, checkMode);
@@ -48038,7 +48639,7 @@
hasSpreadAnyType = true;
}
if (isValidSpreadType(exprType)) {
- spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
}
else {
typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
@@ -48047,7 +48648,7 @@
}
if (!hasSpreadAnyType) {
if (attributesTable.size > 0) {
- spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
}
}
// Handle children attribute
@@ -48075,7 +48676,7 @@
childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
var childPropMap = ts.createSymbolTable();
childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
- spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
}
}
if (hasSpreadAnyType) {
@@ -48093,8 +48694,7 @@
function createJsxAttributesType() {
objectFlags |= freshObjectLiteralFlag;
var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
- result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags;
- result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags;
+ result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
return result;
}
}
@@ -48105,7 +48705,7 @@
// In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
// because then type of children property will have constituent of string type.
if (child.kind === 11 /* JsxText */) {
- if (!child.containsOnlyWhiteSpaces) {
+ if (!child.containsOnlyTriviaWhiteSpaces) {
childrenTypes.push(stringType);
}
}
@@ -48176,7 +48776,7 @@
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 */);
+ var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
if (candidate) {
if (links) {
links.jsxNamespace = candidate;
@@ -48381,7 +48981,7 @@
// Mark local symbol as referenced here because it might not have been marked
// if jsx emit was not react as there wont be error being emitted
reactSym.isReferenced = 67108863 /* All */;
- // If react symbol is alias, mark it as refereced
+ // If react symbol is alias, mark it as referenced
if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) {
markAliasSymbolAsReferenced(reactSym);
}
@@ -48619,6 +49219,15 @@
if (isJSLiteralType(leftType)) {
return anyType;
}
+ if (leftType.symbol === globalThisSymbol) {
+ if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
+ error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
+ }
+ else if (noImplicitAny) {
+ error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
+ }
+ return anyType;
+ }
if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType);
}
@@ -48697,7 +49306,7 @@
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));
+ ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
}
}
function isInPropertyInitializer(node) {
@@ -48706,7 +49315,19 @@
case 154 /* PropertyDeclaration */:
return true;
case 275 /* PropertyAssignment */:
- // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`.
+ case 156 /* MethodDeclaration */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
+ case 277 /* SpreadAssignment */:
+ case 149 /* ComputedPropertyName */:
+ case 216 /* TemplateSpan */:
+ case 270 /* JsxExpression */:
+ case 267 /* JsxAttribute */:
+ case 268 /* JsxAttributes */:
+ case 269 /* JsxSpreadAttribute */:
+ case 262 /* JsxOpeningElement */:
+ case 211 /* ExpressionWithTypeArguments */:
+ case 273 /* HeritageClause */:
return false;
default:
return ts.isExpressionNode(node) ? false : "quit";
@@ -48774,7 +49395,7 @@
}
var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
if (relatedInfo) {
- addRelatedInfo(resultDiagnostic, relatedInfo);
+ ts.addRelatedInfo(resultDiagnostic, relatedInfo);
}
diagnostics.add(resultDiagnostic);
}
@@ -49173,38 +49794,34 @@
return undefined;
}
// 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) {
+ function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
- var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature;
- forEachMatchingParameterType(sourceSignature, signature, function (source, target) {
+ // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
+ // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
+ // for T but leave it possible to later infer '[any]' back to A.
+ var restType = getEffectiveRestType(contextualSignature);
+ var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
+ var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
+ applyToParameterTypes(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, source, target);
});
- if (!contextualMapper) {
- inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */);
+ if (!inferenceContext) {
+ applyToReturnTypes(contextualSignature, signature, function (source, target) {
+ inferTypes(context.inferences, source, target, 8 /* ReturnType */);
+ });
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
}
- function inferJsxTypeArguments(node, signature, excludeArgument, context) {
+ function inferJsxTypeArguments(node, signature, checkMode, context) {
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context);
+ var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
inferTypes(context.inferences, checkAttrType, paramType);
return getInferredTypes(context);
}
- function inferTypeArguments(node, signature, args, excludeArgument, context) {
- // Clear out all the inference results from the last time inferTypeArguments was called on this context
- for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) {
- var inference = _a[_i];
- // As an optimization, we don't have to clear (and later recompute) inferred types
- // for type parameters that have already been fixed on the previous call to inferTypeArguments.
- // It would be just as correct to reset all of them. But then we'd be repeating the same work
- // for the type parameters that were fixed, namely the work done by getInferredType.
- if (!inference.isFixed) {
- inference.inferredType = undefined;
- }
- }
+ function inferTypeArguments(node, signature, args, checkMode, context) {
if (ts.isJsxOpeningLikeElement(node)) {
- return inferJsxTypeArguments(node, signature, excludeArgument, context);
+ return inferJsxTypeArguments(node, signature, checkMode, context);
}
// If a contextual type is available, infer from that type to the return type of the call expression. For
// example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
@@ -49213,10 +49830,11 @@
if (node.kind !== 152 /* Decorator */) {
var contextualType = getContextualType(node);
if (contextualType) {
- // We clone the contextual mapper to avoid disturbing a resolution in progress for an
+ // We clone the inference context to avoid disturbing a resolution in progress for an
// outer call expression. Effectively we just want a snapshot of whatever has been
// inferred for any outer call expression so far.
- var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node)));
+ var outerMapper = getMapperFromContext(cloneInferenceContext(getInferenceContext(node), 1 /* NoDefault */));
+ var instantiatedType = instantiateType(contextualType, outerMapper);
// If the contextual type is a generic function type with a single call signature, we
// instantiate the type with its own type parameters and type arguments. This ensures that
// the type parameters are not erased to type any during type inference such that they can
@@ -49231,6 +49849,9 @@
var inferenceTargetType = getReturnTypeOfSignature(signature);
// Inferences made from return types have lower priority than all other inferences.
inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */);
+ // Create a type mapper for instantiating generic contextual types using the inferences made
+ // from the return type.
+ context.returnMapper = getMapperFromContext(cloneInferredPartOfContext(context));
}
}
var thisType = getThisTypeOfSignature(signature);
@@ -49245,10 +49866,7 @@
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- // For context sensitive arguments we pass the identityMapper, which is a signal to treat all
- // context sensitive function expressions as wildcards
- var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
- var argType = checkExpressionWithContextualType(arg, paramType, mapper);
+ var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
inferTypes(context.inferences, argType, paramType);
}
}
@@ -49272,7 +49890,7 @@
// and the argument are ...x forms.
return arg.kind === 215 /* SyntheticExpression */ ?
createArrayType(arg.type) :
- getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context));
+ getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
}
}
var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType;
@@ -49280,7 +49898,7 @@
var types = [];
var spreadIndex = -1;
for (var i = index; i < argCount; i++) {
- var argType = checkExpressionWithContextualType(args[i], contextualType, context);
+ var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
if (spreadIndex < 0 && isSpreadArgument(args[i])) {
spreadIndex = i - index;
}
@@ -49330,19 +49948,18 @@
* @param node a JSX opening-like element we are trying to figure its call signature
* @param signature a candidate signature we are trying whether it is a call signature
* @param relation a relationship to check parameter and argument type
- * @param excludeArgument
*/
- function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors) {
// Stateless function components can have maximum of three arguments: "props", "context", and "updater".
// However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
// can be specified by users through attributes property.
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined);
+ var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes);
}
- function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignature(node, args, signature, relation, checkMode, reportErrors) {
if (ts.isJsxOpeningLikeElement(node)) {
- return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors);
+ return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors);
}
var thisType = getThisTypeOfSignature(signature);
if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) {
@@ -49364,11 +49981,11 @@
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
- // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter),
+ var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
+ // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
// 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;
+ var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
return false;
}
@@ -49525,25 +50142,41 @@
if (argCount <= max && hasSpreadArgument) {
argCount--;
}
+ var spanArray;
var related;
+ var error = hasRestParameter || hasSpreadArgument ? 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 : ts.Diagnostics.Expected_0_arguments_but_got_1;
if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
if (paramDecl) {
related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined);
}
}
- 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;
- var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount);
- return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1;
- }
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);
}
- var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount);
- return related ? addRelatedInfo(diagnostic, related) : diagnostic;
+ if (!hasSpreadArgument && argCount < min) {
+ var diagnostic_1 = ts.createDiagnosticForNode(node, error, paramRange, argCount);
+ return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
+ }
+ if (hasRestParameter || hasSpreadArgument) {
+ spanArray = ts.createNodeArray(args);
+ if (hasSpreadArgument && argCount) {
+ var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
+ spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
+ }
+ }
+ else {
+ spanArray = ts.createNodeArray(args.slice(max));
+ }
+ spanArray.pos = ts.first(spanArray).pos;
+ spanArray.end = ts.last(spanArray).end;
+ if (spanArray.end === spanArray.pos) {
+ spanArray.end++;
+ }
+ var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
+ return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
}
function getTypeArgumentArityError(node, signatures, typeArguments) {
var argCount = typeArguments.length;
@@ -49573,7 +50206,7 @@
}
return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
}
- function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) {
+ function resolveCall(node, signatures, candidatesOutArray, checkMode, fallbackError) {
var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */;
var isDecorator = node.kind === 152 /* Decorator */;
var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
@@ -49609,7 +50242,7 @@
// For a decorator, no arguments are susceptible to contextual typing due to the fact
// decorators are applied to a declaration by the emitter, and not to an expression.
var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
- var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined;
+ var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
// The following variables are captured and modified by calls to chooseOverload.
// If overload resolution or type argument inference fails, we want to report the
// best error possible. The best error is one which says that an argument was not
@@ -49637,7 +50270,7 @@
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 = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
+ var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 191 /* 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
@@ -49663,12 +50296,7 @@
// skip the checkApplicableSignature check.
if (reportErrors) {
if (candidateForArgumentError) {
- // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...]
- // The importance of excludeArgument is to prevent us from typing function expression parameters
- // in arguments too early. If possible, we'd like to only type them once we know the correct
- // overload. However, this matters for the case where the call is correct. When the call is
- // 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);
+ checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, 0 /* Normal */, /*reportErrors*/ true);
}
else if (candidateForArgumentArityError) {
diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
@@ -49700,7 +50328,7 @@
if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
return undefined;
}
- if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false)) {
candidateForArgumentError = candidate;
return undefined;
}
@@ -49724,9 +50352,10 @@
}
else {
inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
+ typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
+ argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
}
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// 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 (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -49737,21 +50366,21 @@
else {
checkCandidate = candidate;
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
}
continue;
}
- if (excludeArgument) {
+ if (argCheckMode) {
// If one or more context sensitive arguments were excluded, we start including
// them now (and keeping do so for any subsequent candidates) and perform a second
// round of type inference and applicability checking for this particular candidate.
- excludeArgument = undefined;
+ argCheckMode = 0 /* Normal */;
if (inferenceContext) {
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// 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 (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -49759,7 +50388,7 @@
continue;
}
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
@@ -49773,20 +50402,6 @@
return undefined;
}
}
- function getExcludeArgument(args) {
- var excludeArgument;
- // We do not need to call `getEffectiveArgumentCount` here as it only
- // applies when calculating the number of arguments for a decorator.
- for (var i = 0; i < args.length; i++) {
- if (isContextSensitive(args[i])) {
- if (!excludeArgument) {
- excludeArgument = new Array(args.length);
- }
- excludeArgument[i] = true;
- }
- }
- return excludeArgument;
- }
// 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) {
@@ -49875,7 +50490,7 @@
}
function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext);
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
return createSignatureInstantiation(candidate, typeArgumentTypes);
}
function getLongestCandidateIndex(candidates, argsCount) {
@@ -49894,7 +50509,7 @@
}
return maxParamsIndex;
}
- function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveCallExpression(node, candidatesOutArray, checkMode) {
if (node.expression.kind === 98 /* SuperKeyword */) {
var superType = checkSuperExpression(node.expression);
if (isTypeAny(superType)) {
@@ -49910,7 +50525,7 @@
var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
if (baseTypeNode) {
var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
- return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, baseConstructors, candidatesOutArray, checkMode);
}
}
return resolveUntypedCall(node);
@@ -49960,12 +50575,31 @@
}
return resolveErrorCall(node);
}
+ // When a call to a generic function is an argument to an outer call to a generic function for which
+ // inference is in process, we have a choice to make. If the inner call relies on inferences made from
+ // its contextual type to its return type, deferring the inner call processing allows the best possible
+ // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
+ // the inner call, the inner call should be processed early. There's no sure way to know which choice is
+ // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
+ // If no type arguments are specified in the inner call and at least one call signature is generic and
+ // returns a function type, we choose to defer processing. This narrowly permits function composition
+ // operators to flow inferences through return types, but otherwise processes calls right away. We
+ // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
+ // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
+ // from which we never make inferences).
+ if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
+ skippedGenericFunction(node, checkMode);
+ return resolvingSignature;
+ }
// If the function is explicitly marked with `@class`, then it must be constructed.
if (callSignatures.some(function (sig) { return ts.isInJSFile(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);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
+ }
+ function isGenericFunctionReturningFunction(signature) {
+ return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
}
/**
* TS 1.0 spec: 4.12
@@ -49977,7 +50611,7 @@
return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
!numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
}
- function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveNewExpression(node, candidatesOutArray, checkMode) {
if (node.arguments && languageVersion < 1 /* ES5 */) {
var spreadIndex = getSpreadArgumentIndex(node.arguments);
if (spreadIndex >= 0) {
@@ -50025,7 +50659,7 @@
error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
return resolveErrorCall(node);
}
- return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, constructSignatures, candidatesOutArray, checkMode);
}
// 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
@@ -50033,7 +50667,7 @@
// 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, isForSignatureHelp);
+ var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode);
if (!noImplicitAny) {
if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
@@ -50055,13 +50689,12 @@
var firstBase = baseTypes[0];
if (firstBase.flags & 2097152 /* Intersection */) {
var types = firstBase.types;
- var mixinCount = ts.countWhere(types, isMixinConstructorType);
+ var mixinFlags = findMixins(types);
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 (!mixinFlags[i]) {
if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
if (intersectionMember.symbol === target) {
return true;
@@ -50071,6 +50704,7 @@
}
}
}
+ i++;
}
return false;
}
@@ -50114,7 +50748,7 @@
var diagnostic = 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, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
+ invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
}
function invocationErrorRecovery(apparentType, kind, diagnostic) {
if (!apparentType.symbol) {
@@ -50127,10 +50761,10 @@
var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
if (!sigs || !sigs.length)
return;
- 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));
+ 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, isForSignatureHelp) {
+ function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
var tagType = checkExpression(node.tag);
var apparentType = getApparentType(tagType);
if (apparentType === errorType) {
@@ -50146,7 +50780,7 @@
invocationError(node, apparentType, 0 /* Call */);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
}
/**
* Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
@@ -50171,7 +50805,7 @@
/**
* Resolves a decorator as if it were a call expression.
*/
- function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveDecorator(node, candidatesOutArray, checkMode) {
var funcType = checkExpression(node.expression);
var apparentType = getApparentType(funcType);
if (apparentType === errorType) {
@@ -50196,7 +50830,7 @@
invocationErrorRecovery(apparentType, 0 /* Call */, diag);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode, headMessage);
}
function createSignatureForJSXIntrinsic(node, result) {
var namespace = getJsxNamespaceAt(node);
@@ -50215,11 +50849,11 @@
/*hasRestparameter*/ false,
/*hasLiteralTypes*/ false);
}
- function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
var fakeSignature = createSignatureForJSXIntrinsic(node, result);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes);
+ checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
return fakeSignature;
}
var exprTypes = checkExpression(node.tagName);
@@ -50236,7 +50870,7 @@
error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
return resolveErrorCall(node);
}
- return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, signatures, candidatesOutArray, checkMode);
}
/**
* Sometimes, we have a decorator that could accept zero arguments,
@@ -50250,19 +50884,19 @@
signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
});
}
- function resolveSignature(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveSignature(node, candidatesOutArray, checkMode) {
switch (node.kind) {
case 191 /* CallExpression */:
- return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveCallExpression(node, candidatesOutArray, checkMode);
case 192 /* NewExpression */:
- return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveNewExpression(node, candidatesOutArray, checkMode);
case 193 /* TaggedTemplateExpression */:
- return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
case 152 /* Decorator */:
- return resolveDecorator(node, candidatesOutArray, isForSignatureHelp);
+ return resolveDecorator(node, candidatesOutArray, checkMode);
case 262 /* JsxOpeningElement */:
case 261 /* JsxSelfClosingElement */:
- return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp);
+ return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
}
throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
}
@@ -50273,8 +50907,7 @@
* 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, isForSignatureHelp) {
- if (isForSignatureHelp === void 0) { isForSignatureHelp = false; }
+ function getResolvedSignature(node, candidatesOutArray, checkMode) {
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,
@@ -50285,11 +50918,15 @@
return cached;
}
links.resolvedSignature = resolvingSignature;
- var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp);
+ var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
+ // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
+ // resolution should be deferred.
+ if (result !== resolvingSignature) {
// 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.
links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ }
return result;
}
/**
@@ -50365,10 +51002,15 @@
* @param node The call/new expression to be checked.
* @returns On success, the expression's signature's return type. On failure, anyType.
*/
- function checkCallExpression(node) {
+ function checkCallExpression(node, checkMode) {
if (!checkGrammarTypeArguments(node, node.typeArguments))
checkGrammarArguments(node.arguments);
- var signature = getResolvedSignature(node);
+ var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
+ if (signature === resolvingSignature) {
+ // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
+ // returns a function type. We defer checking and return nonInferrableType.
+ return nonInferrableType;
+ }
if (node.expression.kind === 98 /* SuperKeyword */) {
return voidType;
}
@@ -50468,7 +51110,7 @@
var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
anonymousSymbol.type = defaultContainingObject;
- synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0) : defaultContainingObject;
+ synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
}
else {
synthType.syntheticType = type;
@@ -50515,9 +51157,37 @@
function checkAssertion(node) {
return checkAssertionWorker(node, node.type, node.expression);
}
+ function isValidConstAssertionArgument(node) {
+ switch (node.kind) {
+ case 10 /* StringLiteral */:
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 8 /* NumericLiteral */:
+ case 9 /* BigIntLiteral */:
+ case 102 /* TrueKeyword */:
+ case 87 /* FalseKeyword */:
+ case 187 /* ArrayLiteralExpression */:
+ case 188 /* ObjectLiteralExpression */:
+ return true;
+ case 195 /* ParenthesizedExpression */:
+ return isValidConstAssertionArgument(node.expression);
+ case 202 /* PrefixUnaryExpression */:
+ var op = node.operator;
+ var arg = node.operand;
+ return op === 39 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
+ op === 38 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
+ }
+ return false;
+ }
function checkAssertionWorker(errNode, type, expression, checkMode) {
- var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode)));
+ var exprType = checkExpression(expression, checkMode);
+ if (ts.isConstTypeReference(type)) {
+ if (!isValidConstAssertionArgument(expression)) {
+ error(expression, ts.Diagnostics.A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal);
+ }
+ return getRegularTypeOfLiteralType(exprType);
+ }
checkSourceElement(type);
+ exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
var targetType = getTypeFromTypeNode(type);
if (produceDiagnostics && targetType !== errorType) {
var widenedType = getWidenedType(exprType);
@@ -50556,7 +51226,7 @@
}
}
function checkImportMetaProperty(node) {
- if (languageVersion < 6 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) {
+ if (languageVersion < 7 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) {
error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options);
}
var file = ts.getSourceFileOfNode(node);
@@ -50584,7 +51254,7 @@
if (isTupleType(restType)) {
var associatedNames = restType.target.associatedNames;
var index = pos - paramCount;
- return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index;
+ return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
}
return restParameter.escapedName;
}
@@ -50597,33 +51267,37 @@
return getTypeOfParameter(signature.parameters[pos]);
}
if (signature.hasRestParameter) {
+ // We want to return the value undefined for an out of bounds parameter position,
+ // so we need to check bounds here before calling getIndexedAccessType (which
+ // otherwise would return the type 'undefined').
var restType = getTypeOfSymbol(signature.parameters[paramCount]);
- if (isTupleType(restType)) {
- if (pos - paramCount < getLengthOfTupleType(restType)) {
- return restType.typeArguments[pos - paramCount];
- }
- return getRestTypeOfTupleType(restType);
+ var index = pos - paramCount;
+ if (!isTupleType(restType) || restType.target.hasRestElement || index < (restType.typeArguments || ts.emptyArray).length) {
+ return getIndexedAccessType(restType, getLiteralType(index));
}
- return getIndexTypeOfType(restType, 1 /* Number */);
}
return undefined;
}
function getRestTypeAtPosition(source, pos) {
var paramCount = getParameterCount(source);
var restType = getEffectiveRestType(source);
- if (restType && pos === paramCount - 1) {
+ var nonRestCount = paramCount - (restType ? 1 : 0);
+ if (restType && pos === nonRestCount) {
return restType;
}
- var start = restType ? Math.min(pos, paramCount - 1) : pos;
var types = [];
var names = [];
- for (var i = start; i < paramCount; i++) {
+ for (var i = pos; i < nonRestCount; i++) {
types.push(getTypeAtPosition(source, i));
names.push(getParameterNameAtPosition(source, i));
}
+ if (restType) {
+ types.push(getIndexedAccessType(restType, numberType));
+ names.push(getParameterNameAtPosition(source, nonRestCount));
+ }
var minArgumentCount = getMinArgumentCount(source);
- var minLength = minArgumentCount < start ? 0 : minArgumentCount - start;
- return createTupleType(types, minLength, !!restType, names);
+ var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos;
+ return createTupleType(types, minLength, !!restType, /*readonly*/ false, names);
}
function getParameterCount(signature) {
var length = signature.parameters.length;
@@ -50671,16 +51345,27 @@
function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
}
- function inferFromAnnotatedParameters(signature, context, mapper) {
+ function inferFromAnnotatedParameters(signature, context, inferenceContext) {
var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
for (var i = 0; i < len; i++) {
var declaration = signature.parameters[i].valueDeclaration;
if (declaration.type) {
var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
if (typeNode) {
- inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
+ inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
+ }
}
}
+ var restType = getEffectiveRestType(context);
+ if (restType && restType.flags & 262144 /* TypeParameter */) {
+ // The contextual signature has a generic rest parameter. We first instantiate the contextual
+ // signature (without fixing type parameters) and assign types to contextually typed parameters.
+ var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
+ assignContextualParameterTypes(signature, instantiatedContext);
+ // We then infer from a tuple type representing the parameters that correspond to the contextual
+ // rest parameter.
+ var restPos = getParameterCount(context) - 1;
+ inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
}
}
function assignContextualParameterTypes(signature, context) {
@@ -50782,7 +51467,7 @@
var functionFlags = ts.getFunctionFlags(func);
var type;
if (func.body.kind !== 218 /* Block */) {
- type = checkExpressionCached(func.body, checkMode);
+ type = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -50960,7 +51645,7 @@
ts.forEachReturnStatement(func.body, function (returnStatement) {
var expr = returnStatement.expression;
if (expr) {
- var type = checkExpressionCached(expr, checkMode);
+ var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51053,7 +51738,7 @@
ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
checkNodeDeferred(node);
// The identityMapper object is used to indicate that function expressions are wildcards
- if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) {
+ if (checkMode && checkMode & 4 /* 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);
@@ -51063,7 +51748,7 @@
var returnType = getReturnTypeFromBody(node, checkMode);
var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
- returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */;
+ returnOnlyType.objectFlags |= 524288 /* NonInferrableType */;
return links_1.contextFreeType = returnOnlyType;
}
return anyFunctionType;
@@ -51089,12 +51774,12 @@
if (contextualSignature) {
var signature = getSignaturesOfType(type, 0 /* Call */)[0];
if (isContextSensitive(node)) {
- var contextualMapper = getContextualMapper(node);
- if (checkMode === 2 /* Inferential */) {
- inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper);
+ var inferenceContext = getInferenceContext(node);
+ if (checkMode && checkMode & 2 /* Inferential */) {
+ inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
}
- var instantiatedContextualSignature = contextualMapper === identityMapper ?
- contextualSignature : instantiateSignature(contextualSignature, contextualMapper);
+ var instantiatedContextualSignature = inferenceContext ?
+ instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
assignContextualParameterTypes(signature, instantiatedContextualSignature);
}
if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
@@ -51360,13 +52045,13 @@
// Return true if type might be of the given kind. A union or intersection type might be of a given
// kind if at least one constituent type is of the given kind.
function maybeTypeOfKind(type, kind) {
- if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) {
+ if (type.flags & kind & ~131072 /* GenericMappedType */ || kind & 131072 /* GenericMappedType */ && isGenericMappedType(type)) {
return true;
}
if (type.flags & 3145728 /* UnionOrIntersection */) {
var types = type.types;
- for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
- var t = types_15[_i];
+ for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
+ var t = types_16[_i];
if (maybeTypeOfKind(t, kind)) {
return true;
}
@@ -51445,8 +52130,8 @@
if (strictNullChecks && properties.length === 0) {
return checkNonNullType(sourceType, node);
}
- for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) {
- var p = properties_6[_i];
+ for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
+ var p = properties_5[_i];
checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis);
}
return sourceType;
@@ -51470,7 +52155,7 @@
return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
}
else if (property.kind === 277 /* SpreadAssignment */) {
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(property, 4 /* Rest */);
}
var nonRestNames = [];
@@ -51965,7 +52650,7 @@
// Async generator functions prior to ESNext require the __await, __asyncDelegator,
// and __asyncValues helpers
if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ &&
- languageVersion < 6 /* ESNext */) {
+ languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */);
}
// Generator functions prior to ES2015 require the __values helper
@@ -52012,23 +52697,26 @@
}
return node;
}
- function checkExpressionWithContextualType(node, contextualType, contextualMapper) {
+ function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
var context = getContextNode(node);
var saveContextualType = context.contextualType;
- var saveContextualMapper = context.contextualMapper;
+ var saveInferenceContext = context.inferenceContext;
context.contextualType = contextualType;
- context.contextualMapper = contextualMapper;
- var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ :
- contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */;
- var result = checkExpression(node, checkMode);
+ context.inferenceContext = inferenceContext;
+ var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
+ // We strip literal freshness when an appropriate contextual type is present such that contextually typed
+ // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
+ // here would be to not mark contextually typed literals as fresh in the first place.
+ var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
+ getRegularTypeOfLiteralType(type) : type;
context.contextualType = saveContextualType;
- context.contextualMapper = saveContextualMapper;
+ context.inferenceContext = saveInferenceContext;
return result;
}
function checkExpressionCached(node, checkMode) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- if (checkMode) {
+ if (checkMode && checkMode !== 0 /* Normal */) {
return checkExpression(node, checkMode);
}
// When computing a type that we're going to cache, we need to ignore any ongoing control flow
@@ -52091,13 +52779,17 @@
}
return false;
}
- function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
- if (arguments.length === 2) {
- contextualType = getContextualType(node);
+ function isConstContext(node) {
+ var parent = node.parent;
+ return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
+ (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
+ (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
}
+ function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
var type = checkExpression(node, checkMode, forceTuple);
- return isTypeAssertion(node) ? type :
- getWidenedLiteralLikeTypeForContextualType(type, contextualType);
+ return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
+ isTypeAssertion(node) ? type :
+ getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
}
function checkPropertyAssignment(node, checkMode) {
// Do not use hasDynamicName here, because that returns false for well known symbols.
@@ -52121,20 +52813,129 @@
return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
}
function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
+ if (checkMode & 8 /* SkipGenericFunctions */) {
+ skippedGenericFunction(node, checkMode);
+ return anyFunctionType;
+ }
var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType));
if (contextualSignature && !contextualSignature.typeParameters) {
- return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node)));
+ var context = getInferenceContext(node);
+ // We have an expression that is an argument of a generic function for which we are performing
+ // type argument inference. The expression is of a function type with a single generic call
+ // signature and a contextual function type with a single non-generic call signature. Now check
+ // if the outer function returns a function type with a single non-generic call signature and
+ // if some of the outer function type parameters have no inferences so far. If so, we can
+ // potentially add inferred type parameters to the outer function return type.
+ var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature));
+ if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
+ // Instantiate the signature with its own type parameters as type arguments, possibly
+ // renaming the type parameters to ensure they have unique names.
+ var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
+ // Infer from the parameters of the instantiated signature to the parameters of the
+ // contextual signature starting with an empty set of inference candidates.
+ var inferences_2 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
+ applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
+ inferTypes(inferences_2, source, target, /*priority*/ 0, /*contravariant*/ true);
+ });
+ if (ts.some(inferences_2, hasInferenceCandidates)) {
+ // We have inference candidates, indicating that one or more type parameters are referenced
+ // in the parameter types of the contextual signature. Now also infer from the return type.
+ applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
+ inferTypes(inferences_2, source, target);
+ });
+ // If the type parameters for which we produced candidates do not have any inferences yet,
+ // we adopt the new inference candidates and add the type parameters of the expression type
+ // to the set of inferred type parameters for the outer function return type.
+ if (!hasOverlappingInferences(context.inferences, inferences_2)) {
+ mergeInferences(context.inferences, inferences_2);
+ context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
+ return getOrCreateTypeFromSignature(instantiatedSignature);
+ }
+ }
+ }
+ return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
}
}
}
}
return type;
}
+ function skippedGenericFunction(node, checkMode) {
+ if (checkMode & 2 /* Inferential */) {
+ // We have skipped a generic function during inferential typing. Obtain the inference context and
+ // indicate this has occurred such that we know a second pass of inference is be needed.
+ var context = getInferenceContext(node);
+ context.flags |= 4 /* SkippedGenericFunction */;
+ }
+ }
+ function hasInferenceCandidates(info) {
+ return !!(info.candidates || info.contraCandidates);
+ }
+ function hasOverlappingInferences(a, b) {
+ for (var i = 0; i < a.length; i++) {
+ if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ function mergeInferences(target, source) {
+ for (var i = 0; i < target.length; i++) {
+ if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
+ target[i] = source[i];
+ }
+ }
+ }
+ function getUniqueTypeParameters(context, typeParameters) {
+ var result = [];
+ var oldTypeParameters;
+ var newTypeParameters;
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var tp = typeParameters_2[_i];
+ var name = tp.symbol.escapedName;
+ if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
+ var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
+ var symbol = createSymbol(262144 /* TypeParameter */, newName);
+ var newTypeParameter = createTypeParameter(symbol);
+ newTypeParameter.target = tp;
+ oldTypeParameters = ts.append(oldTypeParameters, tp);
+ newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
+ result.push(newTypeParameter);
+ }
+ else {
+ result.push(tp);
+ }
+ }
+ if (newTypeParameters) {
+ var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
+ for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
+ var tp = newTypeParameters_1[_a];
+ tp.mapper = mapper;
+ }
+ }
+ return result;
+ }
+ function hasTypeParameterByName(typeParameters, name) {
+ return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
+ }
+ function getUniqueTypeParameterName(typeParameters, baseName) {
+ var len = baseName.length;
+ while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
+ len--;
+ var s = baseName.slice(0, len);
+ for (var index = 1; true; index++) {
+ var augmentedName = (s + index);
+ if (!hasTypeParameterByName(typeParameters, augmentedName)) {
+ return augmentedName;
+ }
+ }
+ }
/**
* Returns the type of an expression. Unlike checkExpression, this function is simply concerned
* with computing the type and may not fully check all contained sub-expressions for errors.
@@ -52152,7 +52953,7 @@
return getReturnTypeOfSignature(signature);
}
}
- else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) {
+ else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
return getTypeFromTypeNode(expr.type);
}
// Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions
@@ -52174,27 +52975,22 @@
}
var saveContextualType = node.contextualType;
node.contextualType = anyType;
- var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */);
+ var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
node.contextualType = saveContextualType;
return type;
}
- // 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
- // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function
- // object, it serves as an indicator that all contained function and arrow expressions should be considered to
- // have the wildcard function type; this form of type check is used during overload resolution to exclude
- // contextually typed function and arrow expressions in the initial phase.
function checkExpression(node, checkMode, forceTuple) {
- var type;
- if (node.kind === 148 /* QualifiedName */) {
- type = checkQualifiedName(node);
- }
- else {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
- type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
- }
+ var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
if (isConstEnumObjectType(type)) {
+ checkConstEnumAccess(node, type);
+ }
+ currentNode = saveCurrentNode;
+ return type;
+ }
+ function checkConstEnumAccess(node, type) {
// enum object type for const enums are only permitted in:
// - 'left' in property access
// - 'object' in indexed access
@@ -52206,8 +53002,13 @@
if (!ok) {
error(node, ts.Diagnostics.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);
}
+ if (compilerOptions.isolatedModules) {
+ ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
+ var constEnumDeclaration = type.symbol.valueDeclaration;
+ if (constEnumDeclaration.flags & 4194304 /* Ambient */) {
+ error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
+ }
}
- return type;
}
function checkParenthesizedExpression(node, checkMode) {
var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
@@ -52249,6 +53050,8 @@
return checkObjectLiteral(node, checkMode);
case 189 /* PropertyAccessExpression */:
return checkPropertyAccessExpression(node);
+ case 148 /* QualifiedName */:
+ return checkQualifiedName(node);
case 190 /* ElementAccessExpression */:
return checkIndexedAccess(node);
case 191 /* CallExpression */:
@@ -52257,7 +53060,7 @@
}
/* falls through */
case 192 /* NewExpression */:
- return checkCallExpression(node);
+ return checkCallExpression(node, checkMode);
case 193 /* TaggedTemplateExpression */:
return checkTaggedTemplateExpression(node);
case 195 /* ParenthesizedExpression */:
@@ -52322,9 +53125,8 @@
checkSourceElement(node.constraint);
checkSourceElement(node.default);
var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
- if (!hasNonCircularBaseConstraint(typeParameter)) {
- error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter));
- }
+ // Resolve base constraint to reveal circularity errors
+ getBaseConstraintOfType(typeParameter);
if (!hasNonCircularTypeParameterDefault(typeParameter)) {
error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
}
@@ -52366,7 +53168,7 @@
}
// 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) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) {
+ if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) {
error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
}
}
@@ -52377,7 +53179,8 @@
error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
return;
}
- var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent));
+ var signature = getSignatureFromDeclaration(parent);
+ var typePredicate = getTypePredicateOfSignature(signature);
if (!typePredicate) {
return;
}
@@ -52388,12 +53191,12 @@
}
else {
if (typePredicate.parameterIndex >= 0) {
- if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) {
+ if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) {
error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
}
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]), node.type,
+ checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type,
/*headMessage*/ undefined, leadingError);
}
}
@@ -52460,7 +53263,7 @@
var functionFlags = ts.getFunctionFlags(node);
if (!(functionFlags & 4 /* Invalid */)) {
// Async generators prior to ESNext require the __await and __asyncGenerator helpers
- if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) {
+ if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */);
}
// Async functions prior to ES2017 require the __awaiter helper
@@ -52517,7 +53320,7 @@
checkAsyncFunctionReturnType(node, returnTypeNode);
}
}
- if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) {
+ if (node.kind !== 162 /* IndexSignature */ && node.kind !== 294 /* JSDocFunctionType */) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -53196,7 +53999,7 @@
for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) {
var signature = signatures_6[_a];
if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
- error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation);
+ ts.addRelatedInfo(error(signature.declaration, ts.Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), ts.createDiagnosticForNode(bodyDeclaration, ts.Diagnostics.The_implementation_signature_is_declared_here));
break;
}
}
@@ -53273,8 +54076,8 @@
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
// A jsdoc typedef and callback are, by definition, type aliases
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return 2 /* ExportType */;
case 244 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
@@ -53283,7 +54086,7 @@
case 240 /* ClassDeclaration */:
case 243 /* EnumDeclaration */:
return 2 /* ExportType */ | 1 /* ExportValue */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
case 254 /* ExportAssignment */:
// Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
@@ -53648,8 +54451,8 @@
}
function getEntityNameForDecoratorMetadataFromTypeList(types) {
var commonEntityName;
- for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
- var typeNode = types_16[_i];
+ for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
+ var typeNode = types_17[_i];
while (typeNode.kind === 177 /* ParenthesizedType */) {
typeNode = typeNode.type; // Skip parens if need be
}
@@ -53924,7 +54727,7 @@
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
case 246 /* CaseBlock */:
@@ -54017,8 +54820,8 @@
return;
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];
+ for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
+ var typeParameter = typeParameters_3[_i];
if (!isTypeParameterUnused(typeParameter))
continue;
var name = ts.idText(typeParameter.name);
@@ -54271,7 +55074,7 @@
}
// 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 === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
+ if (parent.kind === 284 /* 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));
}
@@ -54286,7 +55089,7 @@
}
// 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 === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
+ if (parent.kind === 284 /* 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));
}
@@ -54343,7 +55146,7 @@
(container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) ||
container.kind === 245 /* ModuleBlock */ ||
container.kind === 244 /* ModuleDeclaration */ ||
- container.kind === 279 /* SourceFile */);
+ container.kind === 284 /* 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
@@ -54443,7 +55246,7 @@
}
}
if (node.kind === 186 /* BindingElement */) {
- if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) {
+ if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 4 /* Rest */);
}
// check computed properties inside property names of binding elements
@@ -54454,7 +55257,7 @@
var parent = node.parent.parent;
var parentType = getTypeForBindingElementParent(parent);
var name = node.propertyName || node.name;
- if (!ts.isBindingPattern(name) && parentType) {
+ if (parentType && !ts.isBindingPattern(name)) {
var exprType = getLiteralTypeFromPropertyName(name);
if (isTypeUsableAsPropertyName(exprType)) {
var nameText = getPropertyNameFromType(exprType);
@@ -54641,7 +55444,7 @@
checkGrammarForInOrForOfStatement(node);
if (node.awaitModifier) {
var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
- if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) {
+ if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 7 /* ESNext */) {
// for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */);
}
@@ -55086,7 +55889,7 @@
// If the function has a return type, but promisedType is
// undefined, an error will be reported in checkAsyncFunctionReturnType
// so we don't need to report one here.
- checkTypeAssignableTo(awaitedType, promisedType, node);
+ checkTypeAssignableToAndOptionallyElaborate(awaitedType, promisedType, node, node.expression);
}
}
else {
@@ -55686,8 +56489,8 @@
for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
var base = baseTypes_2[_i];
var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
- for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) {
- var prop = properties_7[_a];
+ for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
+ var prop = properties_6[_a];
var existing = seen.get(prop.escapedName);
if (!existing) {
seen.set(prop.escapedName, { prop: prop, containingType: base });
@@ -55957,10 +56760,6 @@
checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
checkExportsOnMergedDeclarations(node);
computeEnumMemberValues(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);
- }
// Spec 2014 - Section 9.3:
// It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
// and when an enum type has multiple declarations, only one declaration is permitted to omit a value
@@ -55971,9 +56770,10 @@
var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
if (node === firstDeclaration) {
if (enumSymbol.declarations.length > 1) {
+ var enumIsConst_1 = ts.isEnumConst(node);
// check that const is placed\omitted on all enum declarations
ts.forEach(enumSymbol.declarations, function (decl) {
- if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) {
+ if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
}
});
@@ -56054,8 +56854,8 @@
var symbol = getSymbolOfNode(node);
// The following checks only apply on a non-ambient instantiated module declaration.
if (symbol.flags & 512 /* ValueModule */
- && symbol.declarations.length > 1
&& !inAmbientContext
+ && symbol.declarations.length > 1
&& isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
if (firstNonAmbientClassOrFunc) {
@@ -56196,7 +56996,7 @@
return false;
}
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule) {
error(moduleName, node.kind === 255 /* ExportDeclaration */ ?
ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
@@ -56327,7 +57127,7 @@
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ &&
!node.moduleSpecifier && node.flags & 4194304 /* Ambient */;
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
}
}
@@ -56344,7 +57144,7 @@
}
}
function checkGrammarModuleElementContext(node, errorMessage) {
- var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
+ var isInAppropriateContext = node.parent.kind === 284 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
if (!isInAppropriateContext) {
grammarErrorOnFirstToken(node, errorMessage);
}
@@ -56373,7 +57173,7 @@
// If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
return;
}
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
if (node.isExportEquals) {
error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
@@ -56466,9 +57266,14 @@
!!declaration.body;
}
function checkSourceElement(node) {
- if (!node) {
- return;
+ if (node) {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
+ checkSourceElementWorker(node);
+ currentNode = saveCurrentNode;
+ }
}
+ function checkSourceElementWorker(node) {
if (ts.isInJSFile(node)) {
ts.forEach(node.jsDoc, function (_a) {
var tags = _a.tags;
@@ -56538,32 +57343,32 @@
return checkInferType(node);
case 183 /* ImportType */:
return checkImportType(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return checkJSDocAugmentsTag(node);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return checkJSDocTypeAliasTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return checkJSDocTemplateTag(node);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return checkJSDocTypeTag(node);
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
return checkJSDocParameterTag(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
checkJSDocFunctionType(node);
// falls through
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
- case 292 /* JSDocTypeLiteral */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
+ case 297 /* JSDocTypeLiteral */:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
checkJSDocVariadicType(node);
return;
- case 283 /* JSDocTypeExpression */:
+ case 288 /* JSDocTypeExpression */:
return checkSourceElement(node.type);
case 180 /* IndexedAccessType */:
return checkIndexedAccessType(node);
@@ -56717,10 +57522,13 @@
}
function checkDeferredNodes(context) {
var links = getNodeLinks(context);
- if (!links.deferredNodes) {
- return;
+ if (links.deferredNodes) {
+ links.deferredNodes.forEach(checkDeferredNode);
+ }
}
- links.deferredNodes.forEach(function (node) {
+ function checkDeferredNode(node) {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
switch (node.kind) {
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
@@ -56742,7 +57550,7 @@
checkJsxElementDeferred(node);
break;
}
- });
+ currentNode = saveCurrentNode;
}
function checkSourceFile(node) {
ts.performance.mark("beforeCheck");
@@ -56817,7 +57625,7 @@
throwIfNonDiagnosticsProducing();
if (sourceFile) {
// Some global diagnostics are deferred until they are needed and
- // may not be reported in the firt call to getGlobalDiagnostics.
+ // may not be reported in the first call to getGlobalDiagnostics.
// We should catch these changes and report them.
var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
@@ -56868,7 +57676,7 @@
copySymbols(location.locals, meaning);
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
// falls through
@@ -57087,10 +57895,10 @@
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 299 /* JSDocParameterTag */) {
+ if (entityName.parent.kind === 304 /* JSDocParameterTag */) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) {
+ if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 308 /* JSDocTemplateTag */) {
ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true.
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -57132,7 +57940,7 @@
return undefined;
}
function getSymbolAtLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
}
var parent = node.parent;
@@ -57474,7 +58282,7 @@
}
var parentSymbol_1 = getParentOfSymbol(symbol);
if (parentSymbol_1) {
- if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) {
+ if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 284 /* 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.
@@ -57501,7 +58309,7 @@
return undefined;
}
function isSymbolOfDeclarationWithCollidingName(symbol) {
- if (symbol.flags & 418 /* BlockScoped */) {
+ if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
var links = getSymbolLinks(symbol);
if (links.isDeclarationWithCollidingName === undefined) {
var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
@@ -57589,7 +58397,7 @@
}
function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
- if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
+ if (node === undefined || node.parent.kind !== 284 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
// parent is not source file or it is not reference to internal module
return false;
}
@@ -58018,7 +58826,7 @@
break;
}
}
- if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
+ if (current.valueDeclaration && current.valueDeclaration.kind === 284 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
return false;
}
// check that at least one declaration of top level symbol originates from type declaration file
@@ -58051,7 +58859,7 @@
if (!moduleSymbol) {
return undefined;
}
- return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */);
+ return ts.getDeclarationOfKind(moduleSymbol, 284 /* SourceFile */);
}
function initializeTypeChecker() {
// Bind all source files and propagate errors
@@ -58129,7 +58937,7 @@
// autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
}
- globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1);
+ globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
if (augmentations) {
@@ -58165,8 +58973,8 @@
else {
// Otherwise issue top-level error since the files appear very identical in terms of what they contain
var list = ts.arrayFrom(conflictingSymbols.keys()).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)));
+ diagnostics.add(ts.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(ts.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;
@@ -58283,7 +59091,7 @@
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
}
else if (flags & 128 /* Abstract */) {
@@ -58306,7 +59114,7 @@
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
}
else if (node.kind === 151 /* Parameter */) {
@@ -58351,7 +59159,7 @@
flags |= 1 /* Export */;
break;
case 80 /* DefaultKeyword */:
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
}
@@ -58474,7 +59282,7 @@
case 151 /* Parameter */:
return false;
default:
- if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return false;
}
switch (node.kind) {
@@ -58562,10 +59370,10 @@
var nonSimpleParameters = getNonSimpleParameters(node.parameters);
if (ts.length(nonSimpleParameters)) {
ts.forEach(nonSimpleParameters, function (parameter) {
- addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
+ ts.addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
});
var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); });
- addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
+ ts.addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
return true;
}
}
@@ -59002,6 +59810,11 @@
return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
}
}
+ else if (node.operator === 133 /* ReadonlyKeyword */) {
+ if (node.type.kind !== 169 /* ArrayType */ && node.type.kind !== 170 /* TupleType */) {
+ return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(139 /* SymbolKeyword */));
+ }
+ }
}
function checkGrammarForInvalidDynamicName(node, message) {
if (isNonBindableDynamicName(node)) {
@@ -59392,7 +60205,7 @@
// 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 === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
var links_2 = getNodeLinks(node.parent);
// Check if the containing block ever report this error
if (!links_2.hasReportedStatementInAmbientContext) {
@@ -59432,7 +60245,7 @@
var literalType = ts.isLiteralTypeNode(node.parent) ||
ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
if (!literalType) {
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) {
return true;
}
@@ -59597,10 +60410,11 @@
return createLiteralFromNode(value);
}
ts.createLiteral = createLiteral;
- function createNumericLiteral(value) {
+ function createNumericLiteral(value, numericLiteralFlags) {
+ if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
var node = createSynthesizedNode(8 /* NumericLiteral */);
node.text = value;
- node.numericLiteralFlags = 0;
+ node.numericLiteralFlags = numericLiteralFlags;
return node;
}
ts.createNumericLiteral = createNumericLiteral;
@@ -61445,14 +62259,14 @@
// JSDoc
/* @internal */
function createJSDocTypeExpression(type) {
- var node = createSynthesizedNode(283 /* JSDocTypeExpression */);
+ var node = createSynthesizedNode(288 /* JSDocTypeExpression */);
node.type = type;
return node;
}
ts.createJSDocTypeExpression = createJSDocTypeExpression;
/* @internal */
function createJSDocTypeTag(typeExpression, comment) {
- var tag = createJSDocTag(302 /* JSDocTypeTag */, "type");
+ var tag = createJSDocTag(307 /* JSDocTypeTag */, "type");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61460,7 +62274,7 @@
ts.createJSDocTypeTag = createJSDocTypeTag;
/* @internal */
function createJSDocReturnTag(typeExpression, comment) {
- var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns");
+ var tag = createJSDocTag(305 /* JSDocReturnTag */, "returns");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61468,7 +62282,7 @@
ts.createJSDocReturnTag = createJSDocReturnTag;
/* @internal */
function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
- var tag = createJSDocTag(299 /* JSDocParameterTag */, "param");
+ var tag = createJSDocTag(304 /* JSDocParameterTag */, "param");
tag.typeExpression = typeExpression;
tag.name = name;
tag.isBracketed = isBracketed;
@@ -61478,7 +62292,7 @@
ts.createJSDocParamTag = createJSDocParamTag;
/* @internal */
function createJSDocComment(comment, tags) {
- var node = createSynthesizedNode(291 /* JSDocComment */);
+ var node = createSynthesizedNode(296 /* JSDocComment */);
node.comment = comment;
node.tags = tags;
return node;
@@ -61559,6 +62373,28 @@
return node;
}
ts.createJsxFragment = createJsxFragment;
+ function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
+ var node = createSynthesizedNode(11 /* JsxText */);
+ node.text = text;
+ node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
+ return node;
+ }
+ ts.createJsxText = createJsxText;
+ function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
+ return node.text !== text
+ || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
+ ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
+ : node;
+ }
+ ts.updateJsxText = updateJsxText;
+ function createJsxOpeningFragment() {
+ return createSynthesizedNode(265 /* JsxOpeningFragment */);
+ }
+ ts.createJsxOpeningFragment = createJsxOpeningFragment;
+ function createJsxJsxClosingFragment() {
+ return createSynthesizedNode(266 /* JsxClosingFragment */);
+ }
+ ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment;
function updateJsxFragment(node, openingFragment, children, closingFragment) {
return node.openingFragment !== openingFragment
|| node.children !== children
@@ -61737,7 +62573,7 @@
(typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
(libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
(hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
- var updated = createSynthesizedNode(279 /* SourceFile */);
+ var updated = createSynthesizedNode(284 /* SourceFile */);
updated.flags |= node.flags;
updated.statements = createNodeArray(statements);
updated.endOfFileToken = node.endOfFileToken;
@@ -61821,7 +62657,7 @@
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(307 /* NotEmittedStatement */);
+ var node = createSynthesizedNode(312 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
@@ -61833,7 +62669,7 @@
*/
/* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(316 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -61845,7 +62681,7 @@
*/
/* @internal */
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(310 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(315 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -61860,7 +62696,7 @@
* @param location The location for the expression. Defaults to the positions from "original" if provided.
*/
function createPartiallyEmittedExpression(expression, original) {
- var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */);
+ var node = createSynthesizedNode(313 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -61876,7 +62712,7 @@
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
function flattenCommaElements(node) {
if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
- if (node.kind === 309 /* CommaListExpression */) {
+ if (node.kind === 314 /* CommaListExpression */) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
@@ -61886,7 +62722,7 @@
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(309 /* CommaListExpression */);
+ var node = createSynthesizedNode(314 /* CommaListExpression */);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -61899,33 +62735,197 @@
ts.updateCommaList = updateCommaList;
function createBundle(sourceFiles, prepends) {
if (prepends === void 0) { prepends = ts.emptyArray; }
- var node = ts.createNode(280 /* Bundle */);
+ var node = ts.createNode(285 /* Bundle */);
node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, map) {
- var node = ts.createNode(281 /* UnparsedSource */);
+ var allUnscopedEmitHelpers;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
+ ts.valuesHelper,
+ ts.readHelper,
+ ts.spreadHelper,
+ ts.restHelper,
+ ts.decorateHelper,
+ ts.metadataHelper,
+ ts.paramHelper,
+ ts.awaiterHelper,
+ ts.assignHelper,
+ ts.awaitHelper,
+ ts.asyncGeneratorHelper,
+ ts.asyncDelegator,
+ ts.asyncValues,
+ ts.extendsHelper,
+ ts.templateObjectHelper,
+ ts.generatorHelper,
+ ts.importStarHelper,
+ ts.importDefaultHelper
+ ], function (helper) { return helper.name; }));
+ }
+ function createUnparsedSource() {
+ var node = ts.createNode(286 /* UnparsedSource */);
+ node.prologues = ts.emptyArray;
+ node.referencedFiles = ts.emptyArray;
+ node.libReferenceDirectives = ts.emptyArray;
+ node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
+ return node;
+ }
+ function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
+ var node = createUnparsedSource();
+ var stripInternal;
+ var bundleFileInfo;
if (!ts.isString(textOrInputFiles)) {
ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
- node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath;
+ node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
Object.defineProperties(node, {
text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
});
+ if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
+ node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
+ ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
+ stripInternal = mapTextOrStripInternal;
+ bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
+ if (node.oldFileOfCurrentEmit) {
+ parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo));
+ return node;
+ }
+ }
}
else {
+ node.fileName = "";
node.text = textOrInputFiles;
node.sourceMapPath = mapPathOrType;
- node.sourceMapText = map;
+ node.sourceMapText = mapTextOrStripInternal;
}
+ ts.Debug.assert(!node.oldFileOfCurrentEmit);
+ parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
return node;
}
ts.createUnparsedSourceFile = createUnparsedSourceFile;
- function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapText) {
- var node = ts.createNode(282 /* InputFiles */);
+ function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
+ var prologues;
+ var helpers;
+ var referencedFiles;
+ var typeReferenceDirectives;
+ var libReferenceDirectives;
+ var texts;
+ for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "prologue" /* Prologue */:
+ (prologues || (prologues = [])).push(createUnparsedNode(section, node));
+ break;
+ case "emitHelpers" /* EmitHelpers */:
+ (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ node.hasNoDefaultLib = true;
+ break;
+ case "reference" /* Reference */:
+ (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "type" /* Type */:
+ (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
+ break;
+ case "lib" /* Lib */:
+ (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "prepend" /* Prepend */:
+ var prependNode = createUnparsedNode(section, node);
+ var prependTexts = void 0;
+ for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
+ var text = _c[_b];
+ if (!stripInternal || text.kind !== "internal" /* Internal */) {
+ (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
+ }
+ }
+ prependNode.texts = prependTexts || ts.emptyArray;
+ (texts || (texts = [])).push(prependNode);
+ break;
+ case "internal" /* Internal */:
+ if (stripInternal)
+ break;
+ // falls through
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.prologues = prologues || ts.emptyArray;
+ node.helpers = helpers;
+ node.referencedFiles = referencedFiles || ts.emptyArray;
+ node.typeReferenceDirectives = typeReferenceDirectives;
+ node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
+ node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
+ }
+ function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
+ ts.Debug.assert(!!node.oldFileOfCurrentEmit);
+ var texts;
+ var syntheticReferences;
+ for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "internal" /* Internal */:
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
+ break;
+ // Ignore
+ case "prologue" /* Prologue */:
+ case "emitHelpers" /* EmitHelpers */:
+ case "prepend" /* Prepend */:
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.texts = texts || ts.emptyArray;
+ node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
+ node.syntheticReferences = syntheticReferences;
+ return node;
+ }
+ function mapBundleFileSectionKindToSyntaxKind(kind) {
+ switch (kind) {
+ case "prologue" /* Prologue */: return 279 /* UnparsedPrologue */;
+ case "prepend" /* Prepend */: return 280 /* UnparsedPrepend */;
+ case "internal" /* Internal */: return 282 /* UnparsedInternalText */;
+ case "text" /* Text */: return 281 /* UnparsedText */;
+ case "emitHelpers" /* EmitHelpers */:
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
+ default:
+ return ts.Debug.assertNever(kind);
+ }
+ }
+ function createUnparsedNode(section, parent) {
+ var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ return node;
+ }
+ function createUnparsedSyntheticReference(section, parent) {
+ var node = ts.createNode(283 /* UnparsedSyntheticReference */, section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ node.section = section;
+ return node;
+ }
+ function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
+ var node = ts.createNode(287 /* InputFiles */);
if (!ts.isString(javascriptTextOrReadFileText)) {
var cache_1 = ts.createMap();
var textGetter_1 = function (path) {
@@ -61942,15 +62942,25 @@
var result = textGetter_1(path);
return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
};
+ var buildInfo_1;
+ var getAndCacheBuildInfo_1 = function (getText) {
+ if (buildInfo_1 === undefined) {
+ var result = getText();
+ buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
+ }
+ return buildInfo_1 || undefined;
+ };
node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath;
node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath;
+ node.buildInfoPath = declarationMapTextOrBuildInfoPath;
Object.defineProperties(node, {
javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
- declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } } // TODO:: if there is inline sourceMap in dtsFile, use that
+ declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
+ buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
});
}
else {
@@ -61959,7 +62969,12 @@
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
node.declarationText = declarationTextOrJavascriptPath;
node.declarationMapPath = declarationMapPath;
- node.declarationMapText = declarationMapText;
+ node.declarationMapText = declarationMapTextOrBuildInfoPath;
+ node.javascriptPath = javascriptPath;
+ node.declarationPath = declarationPath,
+ node.buildInfoPath = buildInfoPath;
+ node.buildInfo = buildInfo;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
}
return node;
}
@@ -62097,10 +63112,10 @@
// 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 === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return node.emitNode = { annotatedNodes: [node] };
}
- var sourceFile = ts.getSourceFileOfNode(node);
+ var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
}
node.emitNode = {};
@@ -62398,7 +63413,7 @@
ts.nullTransformationContext = {
enableEmitNotification: ts.noop,
enableSubstitution: ts.noop,
- endLexicalEnvironment: function () { return undefined; },
+ endLexicalEnvironment: ts.returnUndefined,
getCompilerOptions: ts.notImplemented,
getEmitHost: ts.notImplemented,
getEmitResolver: ts.notImplemented,
@@ -62543,38 +63558,38 @@
return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
}
ts.getHelperName = getHelperName;
- var valuesHelper = {
+ ts.valuesHelper = {
name: "typescript:values",
scoped: false,
text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };"
};
function createValuesHelper(context, expression, location) {
- context.requestEmitHelper(valuesHelper);
+ context.requestEmitHelper(ts.valuesHelper);
return ts.setTextRange(ts.createCall(getHelperName("__values"),
/*typeArguments*/ undefined, [expression]), location);
}
ts.createValuesHelper = createValuesHelper;
- var readHelper = {
+ ts.readHelper = {
name: "typescript:read",
scoped: false,
text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };"
};
function createReadHelper(context, iteratorRecord, count, location) {
- context.requestEmitHelper(readHelper);
+ context.requestEmitHelper(ts.readHelper);
return ts.setTextRange(ts.createCall(getHelperName("__read"),
/*typeArguments*/ undefined, count !== undefined
? [iteratorRecord, ts.createLiteral(count)]
: [iteratorRecord]), location);
}
ts.createReadHelper = createReadHelper;
- var spreadHelper = {
+ ts.spreadHelper = {
name: "typescript:spread",
scoped: false,
text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
};
function createSpreadHelper(context, argumentList, location) {
- context.requestEmitHelper(readHelper);
- context.requestEmitHelper(spreadHelper);
+ context.requestEmitHelper(ts.readHelper);
+ context.requestEmitHelper(ts.spreadHelper);
return ts.setTextRange(ts.createCall(getHelperName("__spread"),
/*typeArguments*/ undefined, argumentList), location);
}
@@ -62745,7 +63760,7 @@
function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) {
var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
if (property === firstAccessor) {
- var properties_8 = [];
+ var properties_7 = [];
if (getAccessor) {
var getterFunction = ts.createFunctionExpression(getAccessor.modifiers,
/*asteriskToken*/ undefined,
@@ -62756,7 +63771,7 @@
ts.setTextRange(getterFunction, getAccessor);
ts.setOriginalNode(getterFunction, getAccessor);
var getter = ts.createPropertyAssignment("get", getterFunction);
- properties_8.push(getter);
+ properties_7.push(getter);
}
if (setAccessor) {
var setterFunction = ts.createFunctionExpression(setAccessor.modifiers,
@@ -62768,15 +63783,15 @@
ts.setTextRange(setterFunction, setAccessor);
ts.setOriginalNode(setterFunction, setAccessor);
var setter = ts.createPropertyAssignment("set", setterFunction);
- properties_8.push(setter);
+ properties_7.push(setter);
}
- properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
- properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
+ properties_7.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
+ properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"),
/*typeArguments*/ undefined, [
receiver,
createExpressionForPropertyName(property.name),
- ts.createObjectLiteral(properties_8, multiLine)
+ ts.createObjectLiteral(properties_7, multiLine)
]),
/*location*/ firstAccessor);
return ts.aggregateTransformFlags(expression);
@@ -63420,7 +64435,7 @@
case 190 /* ElementAccessExpression */:
case 189 /* PropertyAccessExpression */:
case 213 /* NonNullExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -63436,7 +64451,7 @@
ts.parenthesizeConciseBody = parenthesizeConciseBody;
function isCommaSequence(node) {
return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
- node.kind === 309 /* CommaListExpression */;
+ node.kind === 314 /* CommaListExpression */;
}
ts.isCommaSequence = isCommaSequence;
var OuterExpressionKinds;
@@ -63455,7 +64470,7 @@
case 212 /* AsExpression */:
case 213 /* NonNullExpression */:
return (kinds & 2 /* Assertions */) !== 0;
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
}
return false;
@@ -63492,7 +64507,7 @@
case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
- case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 313 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
/**
@@ -64284,12 +65299,12 @@
case 278 /* EnumMember */:
return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
// No need to visit nodes with no children.
@@ -64345,7 +65360,7 @@
case 220 /* EmptyStatement */:
case 210 /* OmittedExpression */:
case 236 /* DebuggerStatement */:
- case 307 /* NotEmittedStatement */:
+ case 312 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
@@ -64722,14 +65737,14 @@
result = reduceNode(node.initializer, cbNode, result);
break;
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
result = reduceNodes(node.statements, cbNodes, result);
break;
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -64743,8 +65758,8 @@
return statements;
}
return ts.isNodeArray(statements)
- ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements)
- : ts.addStatementsAfterPrologue(statements, declarations);
+ ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements)
+ : ts.insertStatementsAfterStandardPrologue(statements, declarations);
}
ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
/**
@@ -65010,7 +66025,7 @@
}
exit();
}
- function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) {
+ function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
var _a;
ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
@@ -65020,6 +66035,14 @@
var nameIndexToNewNameIndexMap;
var mappingIterator = decodeMappings(map.mappings);
for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) {
+ if (end && (raw.generatedLine > end.line ||
+ (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
+ break;
+ }
+ if (start && (raw.generatedLine < start.line ||
+ (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
+ continue;
+ }
// Then reencode all the updated mappings into the overall map
var newSourceIndex = void 0;
var newSourceLine = void 0;
@@ -65048,8 +66071,10 @@
}
}
}
- var newGeneratedLine = raw.generatedLine + generatedLine;
- var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter;
+ var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
+ var newGeneratedLine = rawGeneratedLine + generatedLine;
+ var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
+ var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
}
exit();
@@ -65532,7 +66557,7 @@
function chainBundle(transformSourceFile) {
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
+ return node.kind === 284 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
}
function transformBundle(node) {
return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
@@ -66008,8 +67033,8 @@
if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
if (flattenContext.level >= 1 /* ObjectRest */
- && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */))
- && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */))
+ && !(element.transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */))
+ && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */))
&& !ts.isComputedPropertyName(propertyName)) {
bindingElements = ts.append(bindingElements, element);
}
@@ -66075,7 +67100,7 @@
if (flattenContext.level >= 1 /* ObjectRest */) {
// If an array pattern contains an ObjectRest, we must cache the result so that we
// can perform the ObjectRest destructuring in a different declaration
- if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (element.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
if (flattenContext.hoistTempVariables) {
flattenContext.context.hoistVariableDeclaration(temp);
@@ -66193,7 +67218,7 @@
function makeAssignmentElement(name) {
return name;
}
- var restHelper = {
+ ts.restHelper = {
name: "typescript:rest",
scoped: false,
text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
@@ -66202,7 +67227,7 @@
* `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
*/
function createRestCall(context, value, elements, computedTempVariables, location) {
- context.requestEmitHelper(restHelper);
+ context.requestEmitHelper(ts.restHelper);
var propertyNames = [];
var computedTempVariableOffset = 0;
for (var i = 0; i < elements.length - 1; i++) {
@@ -66303,14 +67328,14 @@
var pendingExpressions;
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* 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 === 282 /* InputFiles */) {
+ if (prepend.kind === 287 /* InputFiles */) {
return ts.createUnparsedSourceFile(prepend, "js");
}
return prepend;
@@ -66359,7 +67384,7 @@
*/
function onBeforeVisitNode(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 245 /* ModuleBlock */:
case 218 /* Block */:
@@ -66403,14 +67428,9 @@
* @param node The node to visit.
*/
function visitorWorker(node) {
- if (node.transformFlags & 1 /* TypeScript */) {
- // This node is explicitly marked as TypeScript, so we should transform the node.
+ if (node.transformFlags & 1 /* ContainsTypeScript */) {
return visitTypeScript(node);
}
- else if (node.transformFlags & 2 /* ContainsTypeScript */) {
- // This node contains TypeScript, so we should visit its children.
- return ts.visitEachChild(node, visitor, context);
- }
return node;
}
/**
@@ -66444,7 +67464,7 @@
// As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
// We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
// and will trigger debug failures when debug verbosity is turned up
- if (node.transformFlags & 2 /* ContainsTypeScript */) {
+ if (node.transformFlags & 1 /* ContainsTypeScript */) {
// This node contains TypeScript, so we should visit its children.
return ts.visitEachChild(node, visitor, context);
}
@@ -66486,15 +67506,9 @@
// do not emit ES6 imports and exports since they are illegal inside a namespace
return undefined;
}
- else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
- // This node is explicitly marked as TypeScript, or is exported at the namespace
- // level, so we should transform the node.
+ else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
return visitTypeScript(node);
}
- else if (node.transformFlags & 2 /* ContainsTypeScript */) {
- // This node contains TypeScript, so we should visit its children.
- return ts.visitEachChild(node, visitor, context);
- }
return node;
}
/**
@@ -66545,7 +67559,7 @@
* @param node The node to visit.
*/
function visitTypeScript(node) {
- if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) {
+ if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) {
// TypeScript ambient declarations are elided, but some comments may be preserved.
// See the implementation of `getLeadingComments` in comments.ts for more details.
return ts.createNotEmittedStatement(node);
@@ -66612,7 +67626,7 @@
// See the implementation of `getLeadingComments` in comments.ts for more details.
return ts.createNotEmittedStatement(node);
case 240 /* ClassDeclaration */:
- // This is a class declaration with TypeScript syntax extensions.
+ // This may be a class declaration with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
// - decorators
@@ -66623,7 +67637,7 @@
// - method overload signatures
return visitClassDeclaration(node);
case 209 /* ClassExpression */:
- // This is a class expression with TypeScript syntax extensions.
+ // This may be a class expression with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
// - decorators
@@ -66634,7 +67648,7 @@
// - method overload signatures
return visitClassExpression(node);
case 273 /* HeritageClause */:
- // This is a heritage clause with TypeScript syntax extensions.
+ // This may be a heritage clause with TypeScript syntax extensions.
//
// TypeScript heritage clause extensions include:
// - `implements` clause
@@ -66662,7 +67676,7 @@
// TypeScript arrow functions can have modifiers and type annotations.
return visitArrowFunction(node);
case 151 /* Parameter */:
- // This is a parameter declaration with TypeScript syntax extensions.
+ // This may be a parameter declaration with TypeScript syntax extensions.
//
// TypeScript parameter declaration syntax extensions include:
// - decorators
@@ -66703,7 +67717,8 @@
// TypeScript namespace or external module import.
return visitImportEqualsDeclaration(node);
default:
- return ts.Debug.failBadSyntaxKind(node);
+ // node contains some other TypeScript syntax
+ return ts.visitEachChild(node, visitor, context);
}
}
function visitSourceFile(node) {
@@ -66752,18 +67767,19 @@
facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
return facts;
}
- /**
- * Transforms a class declaration with TypeScript syntax into compatible ES6.
- *
- * This function will only be called when one of the following conditions are met:
- * - The class has decorators.
- * - The class has property declarations with initializers.
- * - The class contains a constructor that contains parameters with accessibility modifiers.
- * - The class is an export in a TypeScript namespace.
- *
- * @param node The node to transform.
- */
+ function hasTypeScriptClassSyntax(node) {
+ return !!(node.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */);
+ }
+ function isClassLikeDeclarationWithTypeScriptSyntax(node) {
+ return ts.some(node.decorators)
+ || ts.some(node.typeParameters)
+ || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
+ || ts.some(node.members, hasTypeScriptClassSyntax);
+ }
function visitClassDeclaration(node) {
+ if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) {
+ return ts.visitEachChild(node, visitor, context);
+ }
var savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
@@ -66816,7 +67832,7 @@
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
var iife = ts.createImmediatelyInvokedArrowFunction(statements);
ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
var varStatement = ts.createVariableStatement(
@@ -66993,16 +68009,10 @@
ts.setCommentRange(statement, node);
return statement;
}
- /**
- * Transforms a class expression with TypeScript syntax into compatible ES6.
- *
- * This function will only be called when one of the following conditions are met:
- * - The class has property declarations with initializers.
- * - The class contains a constructor that contains parameters with accessibility modifiers.
- *
- * @param node The node to transform.
- */
function visitClassExpression(node) {
+ if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
+ return ts.visitEachChild(node, visitor, context);
+ }
var savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
@@ -67066,7 +68076,7 @@
var constructor = ts.getFirstConstructorWithBody(node);
var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty);
var hasParameterPropertyAssignments = constructor &&
- constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ &&
+ constructor.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */ &&
ts.forEach(constructor.parameters, isParameterWithPropertyAssignment);
// If the class does not contain nodes that require a synthesized constructor,
// accept the current constructor if it exists.
@@ -67265,8 +68275,8 @@
* @param receiver The receiver on which each property should be assigned.
*/
function addInitializedPropertyStatements(statements, properties, receiver) {
- for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
- var property = properties_9[_i];
+ for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
+ var property = properties_8[_i];
var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver));
ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
ts.setCommentRange(statement, property);
@@ -67282,8 +68292,8 @@
*/
function generateInitializedPropertyExpressions(properties, receiver) {
var expressions = [];
- for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) {
- var property = properties_10[_i];
+ for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
+ var property = properties_9[_i];
var expression = transformInitializedProperty(property, receiver);
ts.startOnNewLine(expression);
ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
@@ -67357,11 +68367,14 @@
var decorators;
if (node) {
var parameters = node.parameters;
- for (var i = 0; i < parameters.length; i++) {
- var parameter = parameters[i];
+ var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
+ var firstParameterOffset = firstParameterIsThis ? 1 : 0;
+ var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
+ for (var i = 0; i < numParameters; i++) {
+ var parameter = parameters[i + firstParameterOffset];
if (decorators || parameter.decorators) {
if (!decorators) {
- decorators = new Array(parameters.length);
+ decorators = new Array(numParameters);
}
decorators[i] = parameter.decorators;
}
@@ -67861,8 +68874,12 @@
return serializeTypeList(node.types);
case 175 /* ConditionalType */:
return serializeTypeList([node.trueType, node.falseType]);
- case 167 /* TypeQuery */:
case 179 /* TypeOperator */:
+ if (node.operator === 133 /* ReadonlyKeyword */) {
+ return serializeTypeNode(node.type);
+ }
+ break;
+ case 167 /* TypeQuery */:
case 180 /* IndexedAccessType */:
case 181 /* MappedType */:
case 168 /* TypeLiteral */:
@@ -67880,8 +68897,8 @@
// Note when updating logic here also update getEntityNameForDecoratorMetadata
// so that aliases can be marked as referenced
var serializedUnion;
- for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
- var typeNode = types_17[_i];
+ for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
+ var typeNode = types_18[_i];
while (typeNode.kind === 177 /* ParenthesizedType */) {
typeNode = typeNode.type; // Skip parens if need be
}
@@ -68023,7 +69040,7 @@
* available.
*/
function getGlobalBigIntNameWithFallback() {
- return languageVersion < 6 /* ESNext */
+ return languageVersion < 7 /* ESNext */
? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object"))
: ts.createIdentifier("BigInt");
}
@@ -68107,12 +69124,12 @@
* @param node The HeritageClause to transform.
*/
function visitHeritageClause(node) {
- if (node.token === 86 /* ExtendsKeyword */) {
- var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1);
- return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node);
- }
+ if (node.token === 109 /* ImplementsKeyword */) {
+ // implements clauses are elided
return undefined;
}
+ return ts.visitEachChild(node, visitor, context);
+ }
/**
* Transforms an ExpressionWithTypeArguments with TypeScript syntax.
*
@@ -68147,16 +69164,6 @@
}
return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context));
}
- /**
- * Visits a method declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is an overload
- * - The node is marked as abstract, public, private, protected, or readonly
- * - The node has a computed property name
- *
- * @param node The method node.
- */
function visitMethodDeclaration(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return undefined;
@@ -68183,15 +69190,6 @@
function shouldEmitAccessorDeclaration(node) {
return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));
}
- /**
- * Visits a get accessor declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked as abstract, public, private, or protected
- * - The node has a computed property name
- *
- * @param node The get accessor node.
- */
function visitGetAccessor(node) {
if (!shouldEmitAccessorDeclaration(node)) {
return undefined;
@@ -68207,15 +69205,6 @@
}
return updated;
}
- /**
- * Visits a set accessor declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked as abstract, public, private, or protected
- * - The node has a computed property name
- *
- * @param node The set accessor node.
- */
function visitSetAccessor(node) {
if (!shouldEmitAccessorDeclaration(node)) {
return undefined;
@@ -68230,16 +69219,6 @@
}
return updated;
}
- /**
- * Visits a function declaration.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is an overload
- * - The node is exported from a TypeScript namespace
- * - The node has decorators
- *
- * @param node The function node.
- */
function visitFunctionDeclaration(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return ts.createNotEmittedStatement(node);
@@ -68255,14 +69234,6 @@
}
return updated;
}
- /**
- * Visits a function expression node.
- *
- * This function will be called when one of the following conditions are met:
- * - The node has type annotations
- *
- * @param node The function expression node.
- */
function visitFunctionExpression(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return ts.createOmittedExpression();
@@ -68272,51 +69243,31 @@
/*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
return updated;
}
- /**
- * @remarks
- * This function will be called when one of the following conditions are met:
- * - The node has type annotations
- */
function visitArrowFunction(node) {
var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier),
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
/*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
return updated;
}
- /**
- * Visits a parameter declaration node.
- *
- * This function will be called when one of the following conditions are met:
- * - The node has an accessibility modifier.
- * - The node has a questionToken.
- * - The node's kind is ThisKeyword.
- *
- * @param node The parameter declaration node.
- */
function visitParameter(node) {
if (ts.parameterIsThisKeyword(node)) {
return undefined;
}
- var parameter = ts.createParameter(
+ var updated = ts.updateParameter(node,
/*decorators*/ undefined,
/*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName),
/*questionToken*/ undefined,
/*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
+ if (updated !== node) {
// While we emit the source map for the node after skipping decorators and modifiers,
// we need to emit the comments for the original range.
- ts.setOriginalNode(parameter, node);
- ts.setTextRange(parameter, ts.moveRangePastModifiers(node));
- ts.setCommentRange(parameter, node);
- ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node));
- ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */);
- return parameter;
+ ts.setCommentRange(updated, node);
+ ts.setTextRange(updated, ts.moveRangePastModifiers(node));
+ ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
+ ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
+ }
+ return updated;
}
- /**
- * Visits a variable statement in a namespace.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is exported from a TypeScript namespace.
- */
function visitVariableStatement(node) {
if (isExportOfNamespace(node)) {
var variables = ts.getInitializedVariables(node.declarationList);
@@ -68345,12 +69296,6 @@
return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName),
/*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
}
- /**
- * Visits a parenthesized expression that contains either a type assertion or an `as`
- * expression.
- *
- * @param node The parenthesized expression node.
- */
function visitParenthesizedExpression(node) {
var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */);
if (ts.isAssertionExpression(innerExpression)) {
@@ -68487,7 +69432,7 @@
var statements = [];
startLexicalEnvironment();
var members = ts.map(node.members, transformEnumMember);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
ts.addRange(statements, members);
currentNamespaceContainerName = savedCurrentNamespaceLocalName;
return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members),
@@ -68586,7 +69531,7 @@
// 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))
- ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
+ ], currentLexicalScope.kind === 284 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
ts.setOriginalNode(statement, node);
recordEmittedDeclarationInScope(node);
if (isFirstEmittedDeclarationInScope(node)) {
@@ -68734,7 +69679,7 @@
var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
currentNamespaceContainerName = savedCurrentNamespaceContainerName;
currentNamespace = savedCurrentNamespace;
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
@@ -69151,7 +70096,7 @@
// 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 !== 279 /* SourceFile */) {
+ if (container && container.kind !== 284 /* SourceFile */) {
var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) ||
(applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */);
if (substitute) {
@@ -69202,39 +70147,39 @@
argumentsArray.push(descriptor);
}
}
- context.requestEmitHelper(decorateHelper);
+ context.requestEmitHelper(ts.decorateHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"),
/*typeArguments*/ undefined, argumentsArray), location);
}
- var decorateHelper = {
+ ts.decorateHelper = {
name: "typescript:decorate",
scoped: false,
priority: 2,
text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
};
function createMetadataHelper(context, metadataKey, metadataValue) {
- context.requestEmitHelper(metadataHelper);
+ context.requestEmitHelper(ts.metadataHelper);
return ts.createCall(ts.getHelperName("__metadata"),
/*typeArguments*/ undefined, [
ts.createLiteral(metadataKey),
metadataValue
]);
}
- var metadataHelper = {
+ ts.metadataHelper = {
name: "typescript:metadata",
scoped: false,
priority: 3,
text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
};
function createParamHelper(context, expression, parameterOffset, location) {
- context.requestEmitHelper(paramHelper);
+ context.requestEmitHelper(ts.paramHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__param"),
/*typeArguments*/ undefined, [
ts.createLiteral(parameterOffset),
expression
]), location);
}
- var paramHelper = {
+ ts.paramHelper = {
name: "typescript:param",
scoped: false,
priority: 4,
@@ -69289,7 +70234,7 @@
return visited;
}
function visitor(node) {
- if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) {
+ if ((node.transformFlags & 32 /* ContainsES2017 */) === 0) {
return node;
}
switch (node.kind) {
@@ -69559,22 +70504,26 @@
}
var savedCapturedSuperProperties = capturedSuperProperties;
var savedHasSuperElementAccess = hasSuperElementAccess;
+ if (!isArrowFunction) {
capturedSuperProperties = ts.createUnderscoreEscapedMap();
hasSuperElementAccess = false;
+ }
var result;
if (!isArrowFunction) {
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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
if (emitSuperHelpers) {
enableSubstitutionForAsyncMethodsWithSuper();
+ if (ts.hasEntries(capturedSuperProperties)) {
var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
- ts.addStatementsAfterPrologue(statements, [variableStatement]);
+ ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
+ }
}
var block = ts.createBlock(statements, /*multiLine*/ true);
ts.setTextRange(block, node.body);
@@ -69601,8 +70550,10 @@
}
}
enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
+ if (!isArrowFunction) {
capturedSuperProperties = savedCapturedSuperProperties;
hasSuperElementAccess = savedHasSuperElementAccess;
+ }
return result;
}
function transformAsyncFunctionBodyWorker(body, start) {
@@ -69755,7 +70706,7 @@
/* typeParameters */ undefined,
/* parameters */ [],
/* type */ undefined,
- /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name))));
+ /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
if (hasBinding) {
getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(
/* modifiers */ undefined,
@@ -69770,7 +70721,7 @@
/* initializer */ undefined)
],
/* type */ undefined,
- /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v")))));
+ /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v")))));
}
accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter)));
});
@@ -69785,14 +70736,14 @@
], 2 /* Const */));
}
ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
- var awaiterHelper = {
+ ts.awaiterHelper = {
name: "typescript:awaiter",
scoped: false,
priority: 5,
text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
};
function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
- context.requestEmitHelper(awaiterHelper);
+ context.requestEmitHelper(ts.awaiterHelper);
var generatorFunc = ts.createFunctionExpression(
/*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */),
/*name*/ undefined,
@@ -69828,7 +70779,7 @@
/** Enables substitutions for async methods with `super` calls. */
ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
})(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
- function transformESNext(context) {
+ function transformES2018(context) {
var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
var resolver = context.getEmitResolver();
var compilerOptions = context.getCompilerOptions();
@@ -69868,7 +70819,7 @@
return node;
}
function visitorWorker(node, noDestructuringValue) {
- if ((node.transformFlags & 8 /* ContainsESNext */) === 0) {
+ if ((node.transformFlags & 16 /* ContainsES2018 */) === 0) {
return node;
}
switch (node.kind) {
@@ -69912,8 +70863,6 @@
return visitExpressionStatement(node);
case 195 /* ParenthesizedExpression */:
return visitParenthesizedExpression(node, noDestructuringValue);
- case 274 /* CatchClause */:
- return visitCatchClause(node);
case 189 /* PropertyAccessExpression */:
if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) {
capturedSuperProperties.set(node.name.escapedText, true);
@@ -69988,7 +70937,7 @@
return objects;
}
function visitObjectLiteralExpression(node) {
- if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
// spread elements emit like so:
// non-spread elements are chunked together into object literals, and then all are passed to __assign:
// { a, ...o, b } => __assign({a}, o, {b});
@@ -70008,19 +70957,13 @@
function visitParenthesizedExpression(node, noDestructuringValue) {
return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
}
- function visitCatchClause(node) {
- if (!node.variableDeclaration) {
- return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
- }
- return ts.visitEachChild(node, visitor, context);
- }
/**
* Visits a BinaryExpression that contains a destructuring assignment.
*
* @param node A BinaryExpression node.
*/
function visitBinaryExpression(node, noDestructuringValue) {
- if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
}
else if (node.operatorToken.kind === 27 /* CommaToken */) {
@@ -70035,7 +70978,7 @@
*/
function visitVariableDeclaration(node) {
// If we are here it is because the name contains a binding pattern with a rest somewhere in it.
- if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (ts.isBindingPattern(node.name) && node.name.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */);
}
return ts.visitEachChild(node, visitor, context);
@@ -70052,7 +70995,7 @@
* @param node A ForOfStatement.
*/
function visitForOfStatement(node, outermostLabeledStatement) {
- if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.initializer.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
node = transformForOfStatementWithObjectRest(node);
}
if (node.awaitModifier) {
@@ -70149,7 +71092,7 @@
]));
}
function visitParameter(node) {
- if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
// Binding patterns are converted into a generated name and are
// evaluated inside the function body.
return ts.updateParameter(node,
@@ -70262,10 +71205,10 @@
enableSubstitutionForAsyncMethodsWithSuper();
var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
- ts.addStatementsAfterPrologue(statements, [variableStatement]);
+ ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
}
statements.push(returnStatement);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var block = ts.updateBlock(node.body, statements);
if (emitSuperHelpers && hasSuperElementAccess) {
if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
@@ -70291,7 +71234,7 @@
var leadingStatements = endLexicalEnvironment();
if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
- ts.addStatementsAfterPrologue(statements, leadingStatements);
+ ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
ts.addRange(statements, block.statements.slice(statementOffset));
return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
}
@@ -70300,7 +71243,7 @@
function appendObjectRestAssignmentsIfNeeded(statements, node) {
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
- if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (parameter.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
var temp = ts.getGeneratedNameForNode(parameter);
var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp,
/*doNotRecordTempVariablesInLine*/ false,
@@ -70431,8 +71374,8 @@
}
}
}
- ts.transformESNext = transformESNext;
- var assignHelper = {
+ ts.transformES2018 = transformES2018;
+ ts.assignHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
@@ -70443,28 +71386,28 @@
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"),
/*typeArguments*/ undefined, attributesSegments);
}
- context.requestEmitHelper(assignHelper);
+ context.requestEmitHelper(ts.assignHelper);
return ts.createCall(ts.getHelperName("__assign"),
/*typeArguments*/ undefined, attributesSegments);
}
ts.createAssignHelper = createAssignHelper;
- var awaitHelper = {
+ ts.awaitHelper = {
name: "typescript:await",
scoped: false,
text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
};
function createAwaitHelper(context, expression) {
- context.requestEmitHelper(awaitHelper);
+ context.requestEmitHelper(ts.awaitHelper);
return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
}
- var asyncGeneratorHelper = {
+ ts.asyncGeneratorHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
};
function createAsyncGeneratorHelper(context, generatorFunc) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncGeneratorHelper);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncGeneratorHelper);
// Mark this node as originally an async function
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */;
return ts.createCall(ts.getHelperName("__asyncGenerator"),
@@ -70474,24 +71417,24 @@
generatorFunc
]);
}
- var asyncDelegator = {
+ ts.asyncDelegator = {
name: "typescript:asyncDelegator",
scoped: false,
text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
};
function createAsyncDelegatorHelper(context, expression, location) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncDelegator);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncDelegator);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"),
/*typeArguments*/ undefined, [expression]), location);
}
- var asyncValues = {
+ ts.asyncValues = {
name: "typescript:asyncValues",
scoped: false,
text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
};
function createAsyncValuesHelper(context, expression, location) {
- context.requestEmitHelper(asyncValues);
+ context.requestEmitHelper(ts.asyncValues);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"),
/*typeArguments*/ undefined, [expression]), location);
}
@@ -70499,6 +71442,60 @@
/*@internal*/
var ts;
(function (ts) {
+ function transformES2019(context) {
+ return ts.chainBundle(transformSourceFile);
+ function transformSourceFile(node) {
+ if (node.isDeclarationFile) {
+ return node;
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitor(node) {
+ if ((node.transformFlags & 8 /* ContainsES2019 */) === 0) {
+ return node;
+ }
+ switch (node.kind) {
+ case 274 /* CatchClause */:
+ return visitCatchClause(node);
+ default:
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ function visitCatchClause(node) {
+ if (!node.variableDeclaration) {
+ return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ ts.transformES2019 = transformES2019;
+})(ts || (ts = {}));
+/*@internal*/
+var ts;
+(function (ts) {
+ function transformESNext(context) {
+ return ts.chainBundle(transformSourceFile);
+ function transformSourceFile(node) {
+ if (node.isDeclarationFile) {
+ return node;
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitor(node) {
+ if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
+ return node;
+ }
+ switch (node.kind) {
+ default:
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ }
+ ts.transformESNext = transformESNext;
+})(ts || (ts = {}));
+/*@internal*/
+var ts;
+(function (ts) {
function transformJsx(context) {
var compilerOptions = context.getCompilerOptions();
var currentSourceFile;
@@ -70518,7 +71515,7 @@
return visited;
}
function visitor(node) {
- if (node.transformFlags & 4 /* ContainsJsx */) {
+ if (node.transformFlags & 2 /* ContainsJsx */) {
return visitorWorker(node);
}
else {
@@ -70635,7 +71632,7 @@
}
}
function visitJsxText(node) {
- var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, /*includeTrivia*/ true));
+ var fixed = fixupWhitespaceAndDecodeEntities(node.text);
return fixed === undefined ? undefined : ts.createLiteral(fixed);
}
/**
@@ -71020,7 +72017,7 @@
return ts.visitEachChild(node, visitor, context);
}
function visitor(node) {
- if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) {
+ if ((node.transformFlags & 64 /* ContainsES2016 */) === 0) {
return node;
}
switch (node.kind) {
@@ -71100,30 +72097,6 @@
Jump[Jump["Continue"] = 4] = "Continue";
Jump[Jump["Return"] = 8] = "Return";
})(Jump || (Jump = {}));
- var SuperCaptureResult;
- (function (SuperCaptureResult) {
- /**
- * A capture may have been added for calls to 'super', but
- * the caller should emit subsequent statements normally.
- */
- SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement";
- /**
- * A call to 'super()' got replaced with a capturing statement like:
- *
- * var _this = _super.call(...) || this;
- *
- * Callers should skip the current statement.
- */
- SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture";
- /**
- * A call to 'super()' got replaced with a capturing statement like:
- *
- * return _super.call(...) || this;
- *
- * Callers should skip the current statement and avoid any returns of '_this'.
- */
- SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn";
- })(SuperCaptureResult || (SuperCaptureResult = {}));
// Facts we track as we traverse the tree
var HierarchyFacts;
(function (HierarchyFacts) {
@@ -71144,12 +72117,12 @@
HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement";
HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement";
HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper";
- HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName";
// NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
+ // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
//
// Ancestor masks
//
- HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
+ HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 8191] = "AncestorFactsMask";
// We are always in *some* kind of block scope, but only specific block-scope containers are
// top-level or Blocks.
HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
@@ -71159,16 +72132,16 @@
HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes";
// Functions, methods, and accessors are both new lexical scopes and new block scopes.
HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
- HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
+ HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 8094] = "FunctionExcludes";
HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
- HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
+ HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 8086] = "AsyncFunctionBodyExcludes";
// Arrow functions are lexically scoped to their container, but are new block scopes.
HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
- HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes";
+ HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 8064] = "ArrowFunctionExcludes";
// Constructors are both new lexical scopes and new block scopes. Constructors are also
// always considered non-static members of a class.
HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
- HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
+ HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 8086] = "ConstructorExcludes";
// 'do' and 'while' statements are not block scopes. We track that the subtree is contained
// within an IterationStatement to indicate whether the embedded statement is an
// IterationStatementBlock.
@@ -71186,19 +72159,17 @@
HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes";
HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes";
- // Computed property names track subtree flags differently than their containing members.
- HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes";
- HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes";
//
// Subtree facts
//
- HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
- HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName";
+ HierarchyFacts[HierarchyFacts["NewTarget"] = 8192] = "NewTarget";
+ HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 16384] = "CapturedLexicalThis";
//
// Subtree masks
//
- HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
- HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask";
+ HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -8192] = "SubtreeFactsMask";
+ HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
+ HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 24576] = "FunctionSubtreeExcludes";
})(HierarchyFacts || (HierarchyFacts = {}));
function transformES2015(context) {
var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
@@ -71247,7 +72218,7 @@
*/
function enterSubtree(excludeFacts, includeFacts) {
var ancestorFacts = hierarchyFacts;
- hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 8191 /* AncestorFactsMask */;
return ancestorFacts;
}
/**
@@ -71258,7 +72229,7 @@
* @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
*/
function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
- hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -8192 /* SubtreeFactsMask */ | ancestorFacts;
}
function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0
@@ -71280,12 +72251,6 @@
return node;
}
}
- function functionBodyVisitor(node) {
- if (shouldVisitNode(node)) {
- return visitBlock(node, /*isFunctionBody*/ true);
- }
- return node;
- }
function callExpressionVisitor(node) {
if (node.kind === 98 /* SuperKeyword */) {
return visitSuperKeyword(/*isExpressionOfCall*/ true);
@@ -71392,18 +72357,19 @@
}
function visitSourceFile(node) {
var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
+ var prologue = [];
var statements = [];
startLexicalEnvironment();
- var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false);
- addCaptureThisForNodeIfNeeded(statements, node);
- statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor);
+ var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false);
+ statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor);
ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
if (taggedTemplateStringDeclarations) {
statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureThisForNodeIfNeeded(prologue, node);
exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
- return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
+ return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
}
function visitSwitchStatement(node) {
if (convertedLoopState !== undefined) {
@@ -71443,6 +72409,9 @@
return ts.visitEachChild(node, visitor, context);
}
function visitThisKeyword(node) {
+ if (hierarchyFacts & 2 /* ArrowFunction */) {
+ hierarchyFacts |= 16384 /* CapturedLexicalThis */;
+ }
if (convertedLoopState) {
if (hierarchyFacts & 2 /* ArrowFunction */) {
// if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
@@ -71656,7 +72625,7 @@
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
ts.setEmitFlags(block, 1536 /* NoComments */);
return block;
@@ -71684,7 +72653,7 @@
function addConstructor(statements, node, extendsClauseElement) {
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
+ var ancestorFacts = enterSubtree(8086 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
var constructor = ts.getFirstConstructorWithBody(node);
var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
var constructorFunction = ts.createFunctionDeclaration(
@@ -71698,7 +72667,7 @@
ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
}
statements.push(constructorFunction);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
}
/**
@@ -71717,6 +72686,24 @@
return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
|| [];
}
+ function createDefaultConstructorBody(node, isDerivedClass) {
+ // We must be here because the user didn't write a constructor
+ // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
+ // If that's the case we can just immediately return the result of a 'super()' call.
+ var statements = [];
+ resumeLexicalEnvironment();
+ ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
+ if (isDerivedClass) {
+ // return _super !== null && _super.apply(this, arguments) || this;
+ statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
+ }
+ var statementsArray = ts.createNodeArray(statements);
+ ts.setTextRange(statementsArray, node.members);
+ var block = ts.createBlock(statementsArray, /*multiLine*/ true);
+ ts.setTextRange(block, node);
+ ts.setEmitFlags(block, 1536 /* NoComments */);
+ return block;
+ }
/**
* Transforms the body of a constructor declaration of a class.
*
@@ -71727,59 +72714,137 @@
* synthesized `super` call.
*/
function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
+ // determine whether the class is known syntactically to be a derived class (e.g. a
+ // class that extends a value that is not syntactically known to be `null`).
+ var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */;
+ // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
+ // representation:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base { }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // return _super.apply(this, arguments) || this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ if (!constructor)
+ return createDefaultConstructorBody(node, isDerivedClass);
+ // The prologue will contain all leading standard and custom prologue statements added by this transform
+ var prologue = [];
var statements = [];
resumeLexicalEnvironment();
- var statementOffset = -1;
- if (hasSynthesizedSuper) {
// If a super call has already been synthesized,
// we're going to assume that we should just transform everything after that.
// The assumption is that no prior step in the pipeline has added any prologue directives.
- statementOffset = 0;
- }
- else if (constructor) {
- statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false);
- }
- if (constructor) {
+ var statementOffset = 0;
+ if (!hasSynthesizedSuper)
+ statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false);
addDefaultValueAssignmentsIfNeeded(statements, constructor);
addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
- if (!hasSynthesizedSuper) {
- // If no super call has been synthesized, emit custom prologue directives.
+ if (!hasSynthesizedSuper)
statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
+ // If the first statement is a call to `super()`, visit the statement directly
+ var superCallExpression;
+ if (hasSynthesizedSuper) {
+ superCallExpression = createDefaultSuperCallOrThis();
}
- ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!");
+ else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
+ var firstStatement = constructor.body.statements[statementOffset];
+ if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
+ superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
}
- // determine whether the class is known syntactically to be a derived class (e.g. a
- // class that extends a value that is not syntactically known to be `null`).
- var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */;
- var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset);
- // The last statement expression was replaced. Skip it.
- if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) {
- statementOffset++;
}
- if (constructor) {
- if (superCaptureStatus === 1 /* ReplaceSuperCapture */) {
+ if (superCallExpression) {
hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */;
+ statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
}
+ // visit the remaining statements
ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
+ if (isDerivedClass) {
+ if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 2048 /* ContainsLexicalThis */)) {
+ // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
+ // following representation:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base {
+ // constructor() {
+ // super("foo");
+ // }
+ // }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // return _super.call(this, "foo") || this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
+ var returnStatement = ts.createReturn(superCallExpression);
+ ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
+ ts.setEmitFlags(superCall, 1536 /* NoComments */);
+ statements.push(returnStatement);
}
- // Return `_this` unless we're sure enough that it would be pointless to add a return statement.
- // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return.
- if (isDerivedClass
- && superCaptureStatus !== 2 /* ReplaceWithReturn */
- && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) {
+ else {
+ // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base {
+ // constructor() {
+ // super("foo");
+ // this.x = 1;
+ // }
+ // }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // var _this = _super.call(this, "foo") || this;
+ // _this.x = 1;
+ // return _this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ // Since the `super()` call was the first statement, we insert the `this` capturing call to
+ // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
+ insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
+ if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
- if (constructor) {
- prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false);
}
- var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements),
- /*location*/ constructor ? constructor.body.statements : node.members),
- /*multiLine*/ true);
- ts.setTextRange(block, constructor ? constructor.body : node);
- if (!constructor) {
- ts.setEmitFlags(block, 1536 /* NoComments */);
}
+ else {
+ // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
+ // captured when necessitated by an arrow function capturing the lexical `this`:
+ //
+ // ```
+ // // es2015
+ // class C {}
+ //
+ // // es5
+ // var C = (function () {
+ // function C() {
+ // }
+ // return C;
+ // })();
+ // ```
+ insertCaptureThisForNodeIfNeeded(prologue, constructor);
+ }
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)),
+ /*location*/ constructor.body.statements),
+ /*multiLine*/ true);
+ ts.setTextRange(block, constructor.body);
return block;
}
/**
@@ -71809,83 +72874,6 @@
}
return false;
}
- /**
- * Declares a `_this` variable for derived classes and for when arrow functions capture `this`.
- *
- * @returns The new statement offset into the `statements` array.
- */
- function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) {
- // If this isn't a derived class, just capture 'this' for arrow functions if necessary.
- if (!isDerivedClass) {
- if (ctor) {
- addCaptureThisForNodeIfNeeded(statements, ctor);
- }
- return 0 /* NoReplacement */;
- }
- // We must be here because the user didn't write a constructor
- // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
- // If that's the case we can just immediately return the result of a 'super()' call.
- if (!ctor) {
- statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
- return 2 /* ReplaceWithReturn */;
- }
- // The constructor exists, but it and the 'super()' call it contains were generated
- // for something like property initializers.
- // Create a captured '_this' variable and assume it will subsequently be used.
- if (hasSynthesizedSuper) {
- captureThisForNode(statements, ctor, createDefaultSuperCallOrThis());
- enableSubstitutionsForCapturedThis();
- return 1 /* ReplaceSuperCapture */;
- }
- // Most of the time, a 'super' call will be the first real statement in a constructor body.
- // In these cases, we'd like to transform these into a *single* statement instead of a declaration
- // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer,
- // we'd get:
- //
- // var _this;
- // _this = _super.call(...) || this;
- //
- // instead of
- //
- // var _this = _super.call(...) || this;
- //
- // Additionally, if the 'super()' call is the last statement, we should just avoid capturing
- // entirely and immediately return the result like so:
- //
- // return _super.call(...) || this;
- //
- var firstStatement;
- var superCallExpression;
- var ctorStatements = ctor.body.statements;
- if (statementOffset < ctorStatements.length) {
- firstStatement = ctorStatements[statementOffset];
- if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) {
- superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
- }
- }
- // Return the result if we have an immediate super() call on the last statement,
- // but only if the constructor itself doesn't use 'this' elsewhere.
- if (superCallExpression
- && statementOffset === ctorStatements.length - 1
- && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) {
- var returnStatement = ts.createReturn(superCallExpression);
- if (superCallExpression.kind !== 204 /* BinaryExpression */
- || superCallExpression.left.kind !== 191 /* 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.
- ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */)));
- statements.push(returnStatement);
- return 2 /* ReplaceWithReturn */;
- }
- // Perform the capture.
- 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 */;
- }
- return 0 /* NoReplacement */;
- }
function createActualThis() {
return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
}
@@ -71931,14 +72919,9 @@
return node;
}
}
- /**
- * Gets a value indicating whether we need to add default value assignments for a
- * function-like node.
- *
- * @param node A function-like node.
- */
- function shouldAddDefaultValueAssignments(node) {
- return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0;
+ function hasDefaultValueOrBindingPattern(node) {
+ return node.initializer !== undefined
+ || ts.isBindingPattern(node.name);
}
/**
* Adds statements to the body of a function-like node if it contains parameters with
@@ -71948,9 +72931,10 @@
* @param node A function-like node.
*/
function addDefaultValueAssignmentsIfNeeded(statements, node) {
- if (!shouldAddDefaultValueAssignments(node)) {
- return;
+ if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
+ return false;
}
+ var added = false;
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
@@ -71960,12 +72944,14 @@
continue;
}
if (ts.isBindingPattern(name)) {
- addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer);
+ added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
}
else if (initializer) {
- addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
+ insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
+ added = true;
}
}
+ return added;
}
/**
* Adds statements to the body of a function-like node for parameters with binding patterns
@@ -71975,18 +72961,20 @@
* @param name The name of the parameter.
* @param initializer The initializer for the parameter.
*/
- function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
- var temp = ts.getGeneratedNameForNode(parameter);
+ function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
// In cases where a binding pattern is simply '[]' or '{}',
// we usually don't want to emit a var declaration; however, in the presence
// of an initializer, we must emit that expression to preserve side effects.
if (name.elements.length > 0) {
- statements.push(ts.setEmitFlags(ts.createVariableStatement(
- /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */));
+ ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(
+ /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
+ return true;
}
else if (initializer) {
- statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
+ ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
+ return true;
}
+ return false;
}
/**
* Adds statements to the body of a function-like node for parameters with initializers.
@@ -71996,7 +72984,7 @@
* @param name The name of the parameter.
* @param initializer The initializer for the parameter.
*/
- function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
+ function insertDefaultValueAssignmentForInitializer(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.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 */))
@@ -72004,7 +72992,7 @@
ts.startOnNewLine(statement);
ts.setTextRange(statement, parameter);
ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
- statements.push(statement);
+ ts.insertStatementAfterCustomPrologue(statements, statement);
}
/**
* Gets a value indicating whether we need to add statements to handle a rest parameter.
@@ -72027,9 +73015,10 @@
* synthesized call to `super`
*/
function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
+ var prologueStatements = [];
var parameter = ts.lastOrUndefined(node.parameters);
if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
- return;
+ return false;
}
// `declarationName` is the name of the local declaration for the parameter.
var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined);
@@ -72039,7 +73028,7 @@
var restIndex = node.parameters.length - 1;
var temp = ts.createLoopVariable();
// var param = [];
- statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
+ prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList([
ts.createVariableDeclaration(declarationName,
/*type*/ undefined, ts.createArrayLiteral([]))
@@ -72058,25 +73047,30 @@
]));
ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
ts.startOnNewLine(forStatement);
- statements.push(forStatement);
+ prologueStatements.push(forStatement);
if (parameter.name.kind !== 72 /* Identifier */) {
// do the actual destructuring of the rest parameter if necessary
- statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
+ prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
}
+ ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
+ return true;
}
/**
* Adds a statement to capture the `this` of a function declaration if it is needed.
+ * NOTE: This must be executed *after* the subtree has been visited.
*
* @param statements The statements for the new function body.
* @param node A node.
*/
- function addCaptureThisForNodeIfNeeded(statements, node) {
- if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) {
- captureThisForNode(statements, node, ts.createThis());
+ function insertCaptureThisForNodeIfNeeded(statements, node) {
+ if (hierarchyFacts & 16384 /* CapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) {
+ insertCaptureThisForNode(statements, node, ts.createThis());
+ return true;
}
+ return false;
}
- function captureThisForNode(statements, node, initializer) {
+ function insertCaptureThisForNode(statements, node, initializer) {
enableSubstitutionsForCapturedThis();
var captureThisStatement = ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList([
@@ -72085,10 +73079,10 @@
]));
ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
ts.setSourceMapRange(captureThisStatement, node);
- statements.push(captureThisStatement);
+ ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
}
- function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
- if (hierarchyFacts & 16384 /* NewTarget */) {
+ function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
+ if (hierarchyFacts & 8192 /* NewTarget */) {
var newTarget = void 0;
switch (node.kind) {
case 197 /* ArrowFunction */:
@@ -72119,10 +73113,11 @@
ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"),
/*type*/ undefined, newTarget)
]));
+ ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
if (copyOnWrite) {
- return [captureNewTargetStatement].concat(statements);
+ statements = statements.slice();
}
- statements.unshift(captureNewTargetStatement);
+ ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
}
return statements;
}
@@ -72174,7 +73169,6 @@
* @param member The MethodDeclaration node.
*/
function transformClassMethodDeclarationToStatement(receiver, member, container) {
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
var commentRange = ts.getCommentRange(member);
var sourceMapRange = ts.getSourceMapRange(member);
var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name);
@@ -72189,7 +73183,6 @@
// No source map should be emitted for this statement to align with the
// old emitter.
ts.setEmitFlags(statement, 48 /* NoSourceMap */);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return statement;
}
/**
@@ -72215,7 +73208,6 @@
*/
function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
// To align with source maps in the old emitter, the receiver and property name
// arguments are both mapped contiguously to the accessor name.
var target = ts.getMutableClone(receiver);
@@ -72251,7 +73243,6 @@
if (startsOnNewLine) {
ts.startOnNewLine(call);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return call;
}
/**
@@ -72260,12 +73251,12 @@
* @param node An ArrowFunction node.
*/
function visitArrowFunction(node) {
- if (node.transformFlags & 8192 /* ContainsLexicalThis */) {
- enableSubstitutionsForCapturedThis();
+ if (node.transformFlags & 2048 /* ContainsLexicalThis */) {
+ hierarchyFacts |= 16384 /* CapturedLexicalThis */;
}
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
+ var ancestorFacts = enterSubtree(8064 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
var func = ts.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
@@ -72275,7 +73266,11 @@
ts.setTextRange(func, node);
ts.setOriginalNode(func, node);
ts.setEmitFlags(func, 8 /* CapturesThis */);
- exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
+ if (hierarchyFacts & 16384 /* CapturedLexicalThis */) {
+ enableSubstitutionsForCapturedThis();
+ }
+ // If an arrow function contains
+ exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return func;
}
@@ -72286,18 +73281,16 @@
*/
function visitFunctionExpression(node) {
var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
- ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
- : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ ? enterSubtree(8086 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
+ : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & 64 /* ES2015 */
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
- var name = hierarchyFacts & 16384 /* NewTarget */
+ var body = transformFunctionBody(node);
+ var name = hierarchyFacts & 8192 /* NewTarget */
? ts.getLocalName(node)
: node.name;
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.updateFunctionExpression(node,
/*modifiers*/ undefined, node.asteriskToken, name,
@@ -72312,15 +73305,13 @@
function visitFunctionDeclaration(node) {
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & 64 /* ES2015 */
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
- var name = hierarchyFacts & 16384 /* NewTarget */
+ var body = transformFunctionBody(node);
+ var name = hierarchyFacts & 8192 /* NewTarget */
? ts.getLocalName(node)
: node.name;
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.updateFunctionDeclaration(node,
/*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name,
@@ -72338,14 +73329,14 @@
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
- ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
- : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ ? enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
+ : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var parameters = ts.visitParameterList(node.parameters, visitor, context);
var body = transformFunctionBody(node);
- if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) {
+ if (hierarchyFacts & 8192 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) {
name = ts.getGeneratedNameForNode(node);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
/*modifiers*/ undefined, node.asteriskToken, name,
@@ -72363,7 +73354,7 @@
var singleLine = false; // indicates whether the block *may* be emitted as a single line
var statementsLocation;
var closeBraceLocation;
- var leadingStatements = [];
+ var prologue = [];
var statements = [];
var body = node.body;
var statementOffset;
@@ -72371,14 +73362,13 @@
if (ts.isBlock(body)) {
// ensureUseStrict is false because no new prologue-directive should be added.
// addStandardPrologue will put already-existing directives at the beginning of the target statement-array
- statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false);
+ statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false);
}
- addCaptureThisForNodeIfNeeded(leadingStatements, node);
- addDefaultValueAssignmentsIfNeeded(leadingStatements, node);
- addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false);
+ multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
+ multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
if (ts.isBlock(body)) {
// addCustomPrologue puts already-existing directives at the beginning of the target statement-array
- statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor);
+ statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
statementsLocation = body.statements;
ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
// If the original body was a multi-line block, this must be a multi-line block.
@@ -72412,14 +73402,19 @@
// source map location for the close brace.
closeBraceLocation = body;
}
- var lexicalEnvironment = context.endLexicalEnvironment();
- ts.addStatementsAfterPrologue(statements, lexicalEnvironment);
- prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false);
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
+ insertCaptureThisForNodeIfNeeded(prologue, node);
// If we added any final generated statements, this must be a multi-line block
- if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) {
+ if (ts.some(prologue)) {
multiLine = true;
}
- var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine);
+ statements.unshift.apply(statements, prologue);
+ if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
+ // no changes were made, preserve the tree
+ return body;
+ }
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
ts.setTextRange(block, node.body);
if (!multiLine && singleLine) {
ts.setEmitFlags(block, 1 /* SingleLine */);
@@ -72430,11 +73425,6 @@
ts.setOriginalNode(block, node.body);
return block;
}
- function visitFunctionBodyDownLevel(node) {
- var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context);
- return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)),
- /*location*/ updated.statements));
- }
function visitBlock(node, isFunctionBody) {
if (isFunctionBody) {
// A function body is not a block scope.
@@ -72539,7 +73529,7 @@
* @param node A VariableDeclarationList node.
*/
function visitVariableDeclarationList(node) {
- if (node.transformFlags & 64 /* ES2015 */) {
+ if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 65536 /* ContainsBindingPattern */) {
if (node.flags & 3 /* BlockScoped */) {
enableSubstitutionsForBlockScopedBindings();
}
@@ -72552,7 +73542,7 @@
ts.setCommentRange(declarationList, node);
// If the first or last declaration is a binding pattern, we need to modify
// the source map range for the declaration list.
- if (node.transformFlags & 2097152 /* ContainsBindingPattern */
+ if (node.transformFlags & 65536 /* ContainsBindingPattern */
&& (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
}
@@ -72874,7 +73864,7 @@
var numInitialPropertiesWithoutYield = numProperties;
for (var i = 0; i < numProperties; i++) {
var property = properties[i];
- if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
+ if ((property.transformFlags & 131072 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
&& i < numInitialPropertiesWithoutYield) {
numInitialPropertiesWithoutYield = i;
}
@@ -73150,7 +74140,7 @@
*/
function createFunctionForInitializerOfForStatement(node, currentState) {
var functionName = ts.createUniqueName("_loop_init");
- var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ var containsYield = (node.initializer.transformFlags & 131072 /* ContainsYield */) !== 0;
var emitFlags = 0 /* None */;
if (currentState.containsLexicalThis)
emitFlags |= 8 /* CapturesThis */;
@@ -73255,11 +74245,11 @@
statements.push(statement);
}
copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
- ts.addStatementsAfterPrologue(statements, lexicalEnvironment);
+ ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
var loopBody = ts.createBlock(statements, /*multiLine*/ true);
if (ts.isBlock(statement))
ts.setOriginalNode(loopBody, statement);
- var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ var containsYield = (node.statement.transformFlags & 131072 /* ContainsYield */) !== 0;
var emitFlags = 0;
if (currentState.containsLexicalThis)
emitFlags |= 8 /* CapturesThis */;
@@ -73491,13 +74481,11 @@
* @param receiver The receiver for the assignment.
*/
function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
ts.setTextRange(expression, method);
if (startsOnNewLine) {
ts.startOnNewLine(expression);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return expression;
}
function visitCatchClause(node) {
@@ -73549,19 +74537,17 @@
ts.Debug.assert(!ts.isComputedPropertyName(node.name));
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var updated;
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */)
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
+ var body = transformFunctionBody(node);
if (node.kind === 158 /* GetAccessor */) {
updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
}
else {
updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return updated;
}
@@ -73575,10 +74561,7 @@
/*location*/ node);
}
function visitComputedPropertyName(node) {
- var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */);
- var updated = ts.visitEachChild(node, visitor, context);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */);
- return updated;
+ return ts.visitEachChild(node, visitor, context);
}
/**
* Visits a YieldExpression node.
@@ -73595,7 +74578,7 @@
* @param node An ArrayLiteralExpression node.
*/
function visitArrayLiteralExpression(node) {
- if (node.transformFlags & 64 /* ES2015 */) {
+ if (ts.some(node.elements, ts.isSpreadElement)) {
// We are here because we contain a SpreadElementExpression.
return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
}
@@ -73610,7 +74593,10 @@
if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
return visitTypeScriptClassWrapper(node);
}
- if (node.transformFlags & 64 /* ES2015 */) {
+ var expression = ts.skipOuterExpressions(node.expression);
+ if (expression.kind === 98 /* SuperKeyword */ ||
+ ts.isSuperProperty(expression) ||
+ ts.some(node.arguments, ts.isSpreadElement)) {
return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
}
return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression),
@@ -73731,7 +74717,7 @@
function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
// We are here either because SuperKeyword was used somewhere in the expression, or
// because we contain a SpreadElementExpression.
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */ ||
+ if (node.transformFlags & 4096 /* ContainsRestOrSpread */ ||
node.expression.kind === 98 /* SuperKeyword */ ||
ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
@@ -73739,7 +74725,7 @@
ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
}
var resultingCall = void 0;
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */) {
+ if (node.transformFlags & 4096 /* ContainsRestOrSpread */) {
// [source]
// f(...a, b)
// x.m(...a, b)
@@ -73753,7 +74739,7 @@
// _super.apply(this, a.concat([b]))
// _super.m.apply(this, a.concat([b]))
// _super.prototype.m.apply(this, a.concat([b]))
- resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
+ resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
}
else {
// [source]
@@ -73765,13 +74751,11 @@
// _super.call(this, a)
// _super.m.call(this, a)
// _super.prototype.m.call(this, a)
- resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
+ resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
/*location*/ node);
}
if (node.expression.kind === 98 /* SuperKeyword */) {
- var actualThis = ts.createThis();
- ts.setEmitFlags(actualThis, 4 /* NoSubstitution */);
- var initializer = ts.createLogicalOr(resultingCall, actualThis);
+ var initializer = ts.createLogicalOr(resultingCall, createActualThis());
resultingCall = assignToCapturedThis
? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
: initializer;
@@ -73786,7 +74770,7 @@
* @param node A NewExpression node.
*/
function visitNewExpression(node) {
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */) {
+ if (ts.some(node.arguments, ts.isSpreadElement)) {
// We are here because we contain a SpreadElementExpression.
// [source]
// new C(...a)
@@ -74049,12 +75033,7 @@
}
function visitMetaProperty(node) {
if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") {
- if (hierarchyFacts & 8192 /* ComputedPropertyName */) {
- hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */;
- }
- else {
- hierarchyFacts |= 16384 /* NewTarget */;
- }
+ hierarchyFacts |= 8192 /* NewTarget */;
return ts.createFileLevelUniqueName("_newTarget");
}
return node;
@@ -74069,7 +75048,7 @@
function onEmitNode(hint, node, emitCallback) {
if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
// If we are tracking a captured `this`, keep track of the enclosing function.
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
: 65 /* FunctionIncludes */);
previousOnEmitNode(hint, node, emitCallback);
@@ -74249,7 +75228,7 @@
}
ts.transformES2015 = transformES2015;
function createExtendsHelper(context, name) {
- context.requestEmitHelper(extendsHelper);
+ context.requestEmitHelper(ts.extendsHelper);
return ts.createCall(ts.getHelperName("__extends"),
/*typeArguments*/ undefined, [
name,
@@ -74257,20 +75236,20 @@
]);
}
function createTemplateObjectHelper(context, cooked, raw) {
- context.requestEmitHelper(templateObjectHelper);
+ context.requestEmitHelper(ts.templateObjectHelper);
return ts.createCall(ts.getHelperName("__makeTemplateObject"),
/*typeArguments*/ undefined, [
cooked,
raw
]);
}
- var extendsHelper = {
+ ts.extendsHelper = {
name: "typescript:extends",
scoped: false,
priority: 0,
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 = {
+ ts.templateObjectHelper = {
name: "typescript:makeTemplateObject",
scoped: false,
priority: 0,
@@ -74617,7 +75596,7 @@
var withBlockStack; // A stack containing `with` blocks.
return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
- if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
+ if (node.isDeclarationFile || (node.transformFlags & 256 /* ContainsGenerator */) === 0) {
return node;
}
var visited = ts.visitEachChild(node, visitor, context);
@@ -74637,10 +75616,10 @@
else if (inGeneratorFunctionBody) {
return visitJavaScriptInGeneratorFunctionBody(node);
}
- else if (transformFlags & 256 /* Generator */) {
+ else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
return visitGenerator(node);
}
- else if (transformFlags & 512 /* ContainsGenerator */) {
+ else if (transformFlags & 256 /* ContainsGenerator */) {
return ts.visitEachChild(node, visitor, context);
}
else {
@@ -74693,10 +75672,10 @@
case 230 /* ReturnStatement */:
return visitReturnStatement(node);
default:
- if (node.transformFlags & 4194304 /* ContainsYield */) {
+ if (node.transformFlags & 131072 /* ContainsYield */) {
return visitJavaScriptContainingYield(node);
}
- else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) {
+ else if (node.transformFlags & (256 /* ContainsGenerator */ | 262144 /* ContainsHoistedDeclarationOrCompletion */)) {
return ts.visitEachChild(node, visitor, context);
}
else {
@@ -74872,7 +75851,7 @@
var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
transformAndEmitStatements(body.statements, statementOffset);
var buildResult = build();
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
statements.push(ts.createReturn(buildResult));
// Restore previous generator state
inGeneratorFunctionBody = savedInGeneratorFunctionBody;
@@ -74899,7 +75878,7 @@
* @param node The node to visit.
*/
function visitVariableStatement(node) {
- if (node.transformFlags & 4194304 /* ContainsYield */) {
+ if (node.transformFlags & 131072 /* ContainsYield */) {
transformAndEmitVariableDeclarationList(node.declarationList);
return undefined;
}
@@ -75957,7 +76936,7 @@
}
}
function containsYield(node) {
- return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ return !!node && (node.transformFlags & 131072 /* ContainsYield */) !== 0;
}
function countInitialNodesWithoutYield(nodes) {
var numNodes = nodes.length;
@@ -76964,7 +77943,7 @@
}
ts.transformGenerators = transformGenerators;
function createGeneratorHelper(context, body) {
- context.requestEmitHelper(generatorHelper);
+ context.requestEmitHelper(ts.generatorHelper);
return ts.createCall(ts.getHelperName("__generator"),
/*typeArguments*/ undefined, [ts.createThis(), body]);
}
@@ -77027,7 +78006,7 @@
// entering a finally block.
//
// For examples of how these are used, see the comments in ./transformers/generators.ts
- var generatorHelper = {
+ ts.generatorHelper = {
name: "typescript:generator",
scoped: false,
priority: 6,
@@ -77060,7 +78039,7 @@
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* 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.
@@ -77076,7 +78055,7 @@
function transformSourceFile(node) {
if (node.isDeclarationFile ||
!(ts.isEffectiveExternalModule(node, compilerOptions) ||
- node.transformFlags & 16777216 /* ContainsDynamicImport */ ||
+ node.transformFlags & 524288 /* ContainsDynamicImport */ ||
(ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
return node;
}
@@ -77113,7 +78092,7 @@
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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(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
@@ -77339,7 +78318,7 @@
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
// End the lexical environment for the module body
// and merge any new lexical declarations.
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var body = ts.createBlock(statements, /*multiLine*/ true);
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
// If we have any `export * from ...` declarations
@@ -77402,9 +78381,9 @@
return visitFunctionDeclaration(node);
case 240 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
@@ -77413,13 +78392,13 @@
function moduleExpressionElementVisitor(node) {
// This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
// as export/import statements are only transformed at the top level of a file.
- if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) {
+ if (!(node.transformFlags & 524288 /* ContainsDynamicImport */) && !(node.transformFlags & 512 /* ContainsDestructuringAssignment */)) {
return node;
}
if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
- else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) {
+ else if (ts.isDestructuringAssignment(node)) {
return visitDestructuringAssignment(node);
}
else {
@@ -77480,7 +78459,7 @@
}
function visitImportCallExpression(node) {
var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
- var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */);
+ var containsLexicalThis = !!(node.transformFlags & 2048 /* ContainsLexicalThis */);
switch (compilerOptions.module) {
case ts.ModuleKind.AMD:
return createImportCallExpressionAMD(argument, containsLexicalThis);
@@ -77562,7 +78541,7 @@
}
var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]);
}
return promise;
@@ -77576,7 +78555,7 @@
var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
}
var func;
@@ -77610,11 +78589,11 @@
return innerExpr;
}
if (ts.getImportNeedsImportStarHelper(node)) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
}
if (ts.getImportNeedsImportDefaultHelper(node)) {
- context.requestEmitHelper(importDefaultHelper);
+ context.requestEmitHelper(ts.importDefaultHelper);
return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
}
return innerExpr;
@@ -78183,7 +79162,7 @@
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
currentSourceFile = node;
currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
noSubstitution = [];
@@ -78271,7 +79250,7 @@
}
if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)),
/*location*/ node);
}
@@ -78397,13 +79376,13 @@
text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
};
// emit helper for `import * as Name from "foo"`
- var importStarHelper = {
+ ts.importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
// emit helper for `import Name from "foo"`
- var importDefaultHelper = {
+ ts.importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
@@ -78426,7 +79405,7 @@
context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols.
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* 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.
@@ -78445,7 +79424,7 @@
* @param node The SourceFile node.
*/
function transformSourceFile(node) {
- if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) {
+ if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 524288 /* ContainsDynamicImport */)) {
return node;
}
var id = ts.getOriginalNodeId(node);
@@ -78611,7 +79590,7 @@
// 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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
var moduleObject = ts.createObjectLiteral([
ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
@@ -78996,7 +79975,7 @@
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 === 279 /* SourceFile */
+ && (enclosingBlockScopedContainer.kind === 284 /* SourceFile */
|| (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
}
/**
@@ -79339,9 +80318,9 @@
return visitCatchClause(node);
case 218 /* Block */:
return visitBlock(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -79523,14 +80502,13 @@
* @param node The node to visit.
*/
function destructuringAndImportCallVisitor(node) {
- if (node.transformFlags & 1024 /* DestructuringAssignment */
- && node.kind === 204 /* BinaryExpression */) {
+ if (ts.isDestructuringAssignment(node)) {
return visitDestructuringAssignment(node);
}
else if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
- else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) {
+ else if ((node.transformFlags & 512 /* ContainsDestructuringAssignment */) || (node.transformFlags & 524288 /* ContainsDynamicImport */)) {
return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
}
else {
@@ -79589,7 +80567,7 @@
}
else if (ts.isIdentifier(node)) {
var container = resolver.getReferencedExportContainer(node);
- return container !== undefined && container.kind === 279 /* SourceFile */;
+ return container !== undefined && container.kind === 284 /* SourceFile */;
}
else {
return false;
@@ -79622,7 +80600,7 @@
* @param emitCallback A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
var id = ts.getOriginalNodeId(node);
currentSourceFile = node;
moduleInfo = moduleInfoMap[id];
@@ -79831,7 +80809,7 @@
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
}
exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
@@ -79870,7 +80848,7 @@
var previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- context.enableEmitNotification(279 /* SourceFile */);
+ context.enableEmitNotification(284 /* SourceFile */);
context.enableSubstitution(72 /* Identifier */);
var currentSourceFile;
return ts.chainBundle(transformSourceFile);
@@ -79980,7 +80958,8 @@
ts.isImportEqualsDeclaration(node) ||
ts.isTypeAliasDeclaration(node) ||
ts.isConstructorDeclaration(node) ||
- ts.isIndexSignatureDeclaration(node);
+ ts.isIndexSignatureDeclaration(node) ||
+ ts.isPropertyAccessExpression(node);
}
ts.canProduceDiagnostics = canProduceDiagnostics;
function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
@@ -80054,7 +81033,7 @@
}
ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
function createGetSymbolAccessibilityDiagnosticForNode(node) {
- if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
+ if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
return getVariableDeclarationTypeVisibilityError;
}
else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
@@ -80094,7 +81073,7 @@
}
// This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
// The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
- else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ ||
+ else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 189 /* PropertyAccessExpression */ || node.kind === 153 /* PropertySignature */ ||
(node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
// TODO(jfreeman): Deal with computed properties in error reporting.
if (ts.hasModifier(node, 32 /* Static */)) {
@@ -80299,6 +81278,9 @@
case 241 /* InterfaceDeclaration */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
break;
+ case 181 /* MappedType */:
+ diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
+ break;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
@@ -80382,6 +81364,31 @@
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
+ function hasInternalAnnotation(range, currentSourceFile) {
+ var comment = currentSourceFile.text.substring(range.pos, range.end);
+ return ts.stringContains(comment, "@internal");
+ }
+ function isInternalDeclaration(node, currentSourceFile) {
+ var parseTreeNode = ts.getParseTreeNode(node);
+ if (parseTreeNode && parseTreeNode.kind === 151 /* Parameter */) {
+ var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
+ var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
+ var text = currentSourceFile.text;
+ var commentRanges = previousSibling
+ ? ts.concatenate(
+ // to handle
+ // ... parameters, /* @internal */
+ // public param: string
+ ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
+ : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
+ return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
+ }
+ var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
+ return !!ts.forEach(leadingCommentRanges, function (range) {
+ return hasInternalAnnotation(range, currentSourceFile);
+ });
+ }
+ ts.isInternalDeclaration = isInternalDeclaration;
var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
2048 /* WriteClassExpressionAsTypeLiteral */ |
4096 /* UseTypeOfFunction */ |
@@ -80510,10 +81517,10 @@
}
}
function transformRoot(node) {
- if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
+ if (node.kind === 284 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
}
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
isBundledEmit = true;
refs = ts.createMap();
libs = ts.createMap();
@@ -80543,9 +81550,15 @@
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 === 282 /* InputFiles */) {
- return ts.createUnparsedSourceFile(prepend, "dts");
+ if (prepend.kind === 287 /* InputFiles */) {
+ var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
+ hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
+ collectReferences(sourceFile, refs);
+ recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
+ collectLibs(sourceFile, libs);
+ return sourceFile;
}
+ return prepend;
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -80637,7 +81650,7 @@
}
}
function collectReferences(sourceFile, ret) {
- if (noResolve || ts.isSourceFileJS(sourceFile))
+ if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
return ret;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
@@ -81184,7 +82197,9 @@
if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
return undefined;
}
+ getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker);
+ getSymbolAccessibilityDiagnostic = oldDiag;
var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
});
@@ -81227,7 +82242,7 @@
if (ctor) {
var oldDiag_1 = getSymbolAccessibilityDiagnostic;
parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
- if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */))
+ if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
return;
getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
if (param.name.kind === 72 /* Identifier */) {
@@ -81363,18 +82378,8 @@
}
errorNameNode = undefined;
}
- function hasInternalAnnotation(range) {
- var comment = currentSourceFile.text.substring(range.pos, range.end);
- return ts.stringContains(comment, "@internal");
- }
function shouldStripInternal(node) {
- if (stripInternal && node) {
- var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile);
- if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
- return true;
- }
- }
- return false;
+ return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
}
function isScopeMarker(node) {
return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
@@ -81396,7 +82401,7 @@
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 === 279 /* SourceFile */;
+ var parentIsFile = node.parent.kind === 284 /* SourceFile */;
if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */);
additions = 0 /* None */;
@@ -81565,9 +82570,15 @@
if (jsx === 2 /* React */) {
transformers.push(ts.transformJsx);
}
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
transformers.push(ts.transformESNext);
}
+ if (languageVersion < 6 /* ES2019 */) {
+ transformers.push(ts.transformES2019);
+ }
+ if (languageVersion < 5 /* ES2018 */) {
+ transformers.push(ts.transformES2018);
+ }
if (languageVersion < 4 /* ES2017 */) {
transformers.push(ts.transformES2017);
}
@@ -81607,7 +82618,7 @@
* @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(312 /* Count */);
+ var enabledSyntaxKindFeatures = new Array(317 /* Count */);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -81867,10 +82878,14 @@
})(ts || (ts = {}));
var ts;
(function (ts) {
- var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
var syntheticParent = { pos: -1, end: -1 };
/*@internal*/
+ function isBuildInfoFile(file) {
+ return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
+ }
+ ts.isBuildInfoFile = isBuildInfoFile;
+ /*@internal*/
/**
* Iterates over the source files that are expected to have an emit output.
*
@@ -81880,13 +82895,14 @@
* 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, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
+ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles, onlyBuildInfo, includeBuildInfo) {
if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; }
var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
+ var prepends = host.getPrependNodes();
+ if (sourceFiles.length || prepends.length) {
+ var bundle = ts.createBundle(sourceFiles, prepends);
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -81894,6 +82910,7 @@
}
}
else {
+ if (!onlyBuildInfo) {
for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
var sourceFile = sourceFiles_1[_a];
var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
@@ -81902,23 +82919,52 @@
}
}
}
+ if (includeBuildInfo) {
+ var buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
+ if (buildInfoPath)
+ return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
+ }
+ }
}
ts.forEachEmittedFile = forEachEmittedFile;
/*@internal*/
+ function getOutputPathForBuildInfo(options) {
+ var configFile = options.configFilePath;
+ if (!configFile || !ts.isIncrementalCompilation(options))
+ return undefined;
+ if (options.tsBuildInfoFile)
+ return options.tsBuildInfoFile;
+ var outPath = options.outFile || options.out;
+ var buildInfoExtensionLess;
+ if (outPath) {
+ buildInfoExtensionLess = ts.removeFileExtension(outPath);
+ }
+ else {
+ var configFileExtensionLess = ts.removeFileExtension(configFile);
+ buildInfoExtensionLess = options.outDir ?
+ options.rootDir ?
+ ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
+ ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
+ configFileExtensionLess;
+ }
+ return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
+ }
+ ts.getOutputPathForBuildInfo = getOutputPathForBuildInfo;
+ /*@internal*/
function getOutputPathsForBundle(options, forceDtsPaths) {
var outPath = options.outFile || options.out;
var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
var declarationMapPath = declarationFilePath && 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 };
+ var buildInfoPath = getOutputPathForBuildInfo(options);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
}
ts.getOutputPathsForBundle = getOutputPathsForBundle;
/*@internal*/
function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
var options = host.getCompilerOptions();
- if (sourceFile.kind === 280 /* Bundle */) {
+ if (sourceFile.kind === 285 /* Bundle */) {
return getOutputPathsForBundle(options, forceDtsPaths);
}
else {
@@ -81932,19 +82978,13 @@
var isJs = ts.isSourceFileJS(sourceFile);
var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
}
}
ts.getOutputPathsFor = getOutputPathsFor;
function getSourceMapFilePath(jsFilePath, options) {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
- function createDefaultBundleInfo() {
- return {
- originalOffset: -1,
- totalLength: -1
- };
- }
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
@@ -81967,9 +83007,91 @@
return ".js" /* Js */;
}
ts.getOutputExtension = getOutputExtension;
+ function rootDirOfOptions(configFile) {
+ return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.assertDefined(configFile.options.configFilePath));
+ }
+ function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
+ return outputDir ?
+ ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
+ inputFileName;
+ }
+ /* @internal */
+ function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
+ ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(inputFileName));
+ return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
+ }
+ ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
+ function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
+ var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
+ var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
+ ".json" /* Json */ :
+ ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
+ ".jsx" /* Jsx */ :
+ ".js" /* Js */);
+ return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.assertDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
+ outputFileName :
+ undefined;
+ }
+ /*@internal*/
+ function getAllProjectOutputs(configFile, ignoreCase) {
+ var outputs;
+ var addOutput = function (path) { return path && (outputs || (outputs = [])).push(path); };
+ if (configFile.options.outFile || configFile.options.out) {
+ var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ addOutput(jsFilePath);
+ addOutput(sourceMapFilePath);
+ addOutput(declarationFilePath);
+ addOutput(declarationMapPath);
+ addOutput(buildInfoPath);
+ }
+ else {
+ for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
+ var inputFileName = _c[_b];
+ if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
+ continue;
+ var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ addOutput(js);
+ if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
+ continue;
+ if (configFile.options.sourceMap) {
+ addOutput(js + ".map");
+ }
+ if (ts.getEmitDeclarations(configFile.options) && ts.hasTSFileExtension(inputFileName)) {
+ var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
+ addOutput(dts);
+ if (configFile.options.declarationMap) {
+ addOutput(dts + ".map");
+ }
+ }
+ }
+ addOutput(getOutputPathForBuildInfo(configFile.options));
+ }
+ return outputs || ts.emptyArray;
+ }
+ ts.getAllProjectOutputs = getAllProjectOutputs;
+ /*@internal*/
+ function getFirstProjectOutput(configFile, ignoreCase) {
+ if (configFile.options.outFile || configFile.options.out) {
+ var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
+ return ts.Debug.assertDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
+ }
+ for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
+ var inputFileName = _b[_a];
+ if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
+ continue;
+ var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ if (jsFilePath)
+ return jsFilePath;
+ }
+ var buildInfoPath = getOutputPathForBuildInfo(configFile.options);
+ if (buildInfoPath)
+ return buildInfoPath;
+ return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
+ }
+ ts.getFirstProjectOutput = getFirstProjectOutput;
/*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers, onlyBuildInfo) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -81977,12 +83099,12 @@
var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
var writer = ts.createTextWriter(newLine);
var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit;
- var bundleInfo = createDefaultBundleInfo();
+ var bundleBuildInfo;
var emitSkipped = false;
var exportedModulesFromDeclarationEmit;
// Emit each output file
enter();
- forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles);
+ forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile);
exit();
return {
emitSkipped: emitSkipped,
@@ -81992,9 +83114,16 @@
exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
+ bundleBuildInfo = {
+ commonSourceDirectory: host.getCommonSourceDirectory(),
+ sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return file.fileName; })
+ };
+ }
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
+ emitBuildInfo(bundleBuildInfo, buildInfoPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
if (jsFilePath) {
@@ -82003,8 +83132,8 @@
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
- if (bundleInfoPath) {
- emittedFilesList.push(bundleInfoPath);
+ if (buildInfoPath) {
+ emittedFilesList.push(buildInfoPath);
}
}
if (declarationFilePath) {
@@ -82015,8 +83144,21 @@
}
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
- if (emitOnlyDtsFiles || !jsFilePath) {
+ function emitBuildInfo(bundle, buildInfoPath) {
+ // Write build information if applicable
+ if (!buildInfoPath || targetSourceFile || emitSkipped)
+ return;
+ var program = host.getProgramBuildInfo();
+ if (!bundle && !program)
+ return;
+ if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
+ emitSkipped = true;
+ return;
+ }
+ ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: ts.version }), /*writeByteOrderMark*/ false);
+ }
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
+ if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
return;
}
// Make sure not to write js file and source map file if any of them cannot be written
@@ -82036,6 +83178,7 @@
inlineSourceMap: compilerOptions.inlineSourceMap,
inlineSources: compilerOptions.inlineSources,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ writeBundleFileInfo: !!bundleBuildInfo
};
// Create a printer to print the nodes
var printer = createPrinter(printerOptions, {
@@ -82046,12 +83189,14 @@
substituteNode: transform.substituteNode,
});
ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions);
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
// Clean up emit nodes on parse tree
transform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.js = printer.bundleFileInfo;
}
function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) {
- if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
+ if (!sourceFileOrBundle || !(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
return;
}
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
@@ -82080,6 +83225,8 @@
inlineSourceMap: compilerOptions.inlineSourceMap,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
onlyPrintJsDocStyle: true,
+ writeBundleFileInfo: !!bundleBuildInfo,
+ recordInternalSection: !!bundleBuildInfo
};
var declarationPrinter = createPrinter(printerOptions, {
// resolver hooks
@@ -82092,18 +83239,20 @@
emitSkipped = emitSkipped || declBlocked;
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, {
+ printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
sourceMap: compilerOptions.declarationMap,
sourceRoot: compilerOptions.sourceRoot,
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
- if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) {
+ if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 284 /* SourceFile */) {
var sourceFile = declarationTransform.transformed[0];
exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
}
}
declarationTransform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
}
function collectLinkedAliases(node) {
if (ts.isExportAssignment(node)) {
@@ -82118,16 +83267,16 @@
}
ts.forEachChild(node, collectLinkedAliases);
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) {
- var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined;
- var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined;
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
+ var bundle = sourceFileOrBundle.kind === 285 /* Bundle */ ? sourceFileOrBundle : undefined;
+ var sourceFile = sourceFileOrBundle.kind === 284 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
var sourceMapGenerator;
if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
}
if (bundle) {
- printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator);
+ printer.writeBundle(bundle, writer, sourceMapGenerator);
}
else {
printer.writeFile(sourceFile, writer, sourceMapGenerator);
@@ -82156,18 +83305,12 @@
}
// Write the output file
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
- // Write bundled offset information if applicable
- if (bundleInfoPath) {
- bundleInfo.totalLength = writer.getTextPos();
- ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false);
- }
// Reset state
writer.clear();
- bundleInfo = createDefaultBundleInfo();
}
function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
- && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
+ && (sourceFileOrBundle.kind !== 284 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
}
function getSourceRoot(mapOptions) {
// Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
@@ -82224,6 +83367,167 @@
}
}
ts.emitFiles = emitFiles;
+ /*@internal*/
+ function getBuildInfoText(buildInfo) {
+ return JSON.stringify(buildInfo, undefined, 2);
+ }
+ ts.getBuildInfoText = getBuildInfoText;
+ /*@internal*/
+ function getBuildInfo(buildInfoText) {
+ return JSON.parse(buildInfoText);
+ }
+ ts.getBuildInfo = getBuildInfo;
+ /*@internal*/
+ ts.notImplementedResolver = {
+ hasGlobalName: ts.notImplemented,
+ getReferencedExportContainer: ts.notImplemented,
+ getReferencedImportDeclaration: ts.notImplemented,
+ getReferencedDeclarationWithCollidingName: ts.notImplemented,
+ isDeclarationWithCollidingName: ts.notImplemented,
+ isValueAliasDeclaration: ts.notImplemented,
+ isReferencedAliasDeclaration: ts.notImplemented,
+ isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
+ getNodeCheckFlags: ts.notImplemented,
+ isDeclarationVisible: ts.notImplemented,
+ isLateBound: function (_node) { return false; },
+ collectLinkedAliases: ts.notImplemented,
+ isImplementationOfOverload: ts.notImplemented,
+ isRequiredInitializedParameter: ts.notImplemented,
+ isOptionalUninitializedParameterProperty: ts.notImplemented,
+ isExpandoFunctionDeclaration: ts.notImplemented,
+ getPropertiesOfContainerFunction: ts.notImplemented,
+ createTypeOfDeclaration: ts.notImplemented,
+ createReturnTypeOfSignatureDeclaration: ts.notImplemented,
+ createTypeOfExpression: ts.notImplemented,
+ createLiteralConstValue: ts.notImplemented,
+ isSymbolAccessible: ts.notImplemented,
+ isEntityNameVisible: ts.notImplemented,
+ // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
+ getConstantValue: ts.notImplemented,
+ getReferencedValueDeclaration: ts.notImplemented,
+ getTypeReferenceSerializationKind: ts.notImplemented,
+ isOptionalParameter: ts.notImplemented,
+ moduleExportsSomeValue: ts.notImplemented,
+ isArgumentsLocalBinding: ts.notImplemented,
+ getExternalModuleFileFromDeclaration: ts.notImplemented,
+ getTypeReferenceDirectivesForEntityName: ts.notImplemented,
+ getTypeReferenceDirectivesForSymbol: ts.notImplemented,
+ isLiteralConstDeclaration: ts.notImplemented,
+ getJsxFactoryEntity: ts.notImplemented,
+ getAllAccessorDeclarations: ts.notImplemented,
+ getSymbolOfExternalModuleSpecifier: ts.notImplemented,
+ isBindingCapturedByNode: ts.notImplemented,
+ };
+ function createSourceFilesFromBundleBuildInfo(bundle) {
+ var sourceFiles = bundle.sourceFiles.map(function (fileName) {
+ var sourceFile = ts.createNode(284 /* SourceFile */, 0, 0);
+ sourceFile.fileName = fileName;
+ sourceFile.text = "";
+ sourceFile.statements = ts.createNodeArray();
+ return sourceFile;
+ });
+ var jsBundle = ts.Debug.assertDefined(bundle.js);
+ ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
+ var sourceFile = sourceFiles[prologueInfo.file];
+ sourceFile.text = prologueInfo.text;
+ sourceFile.end = prologueInfo.text.length;
+ sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
+ var statement = ts.createNode(221 /* ExpressionStatement */, directive.pos, directive.end);
+ statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
+ statement.expression.text = directive.expression.text;
+ return statement;
+ }));
+ });
+ return sourceFiles;
+ }
+ /*@internal*/
+ function emitUsingBuildInfo(config, host, getCommandLine) {
+ var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
+ var buildInfoText = host.readFile(ts.Debug.assertDefined(buildInfoPath));
+ if (!buildInfoText)
+ return buildInfoPath;
+ var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath));
+ if (!jsFileText)
+ return jsFilePath;
+ var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
+ // error if no source map or for now if inline sourcemap
+ if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
+ return sourceMapFilePath || "inline sourcemap decoding";
+ // read declaration text
+ var declarationText = declarationFilePath && host.readFile(declarationFilePath);
+ if (declarationFilePath && !declarationText)
+ return declarationFilePath;
+ var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
+ // error if no source map or for now if inline sourcemap
+ if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
+ return declarationMapPath || "inline sourcemap decoding";
+ var buildInfo = getBuildInfo(buildInfoText);
+ if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
+ return buildInfoPath;
+ var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo,
+ /*onlyOwnText*/ true);
+ var outputFiles = [];
+ var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
+ var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle);
+ var emitHost = {
+ getPrependNodes: ts.memoize(function () { return prependNodes.concat([ownPrependInput]); }),
+ getCanonicalFileName: host.getCanonicalFileName,
+ getCommonSourceDirectory: function () { return buildInfo.bundle.commonSourceDirectory; },
+ getCompilerOptions: function () { return config.options; },
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ getNewLine: function () { return host.getNewLine(); },
+ getSourceFile: ts.returnUndefined,
+ getSourceFileByPath: ts.returnUndefined,
+ getSourceFiles: function () { return sourceFilesForJsEmit; },
+ getLibFileFromReference: ts.notImplemented,
+ isSourceFileFromExternalLibrary: ts.returnFalse,
+ getResolvedProjectReferenceToRedirect: ts.returnUndefined,
+ writeFile: function (name, text, writeByteOrderMark) {
+ switch (name) {
+ case jsFilePath:
+ if (jsFileText === text)
+ return;
+ break;
+ case sourceMapFilePath:
+ if (sourceMapText === text)
+ return;
+ break;
+ case buildInfoPath:
+ var newBuildInfo = getBuildInfo(text);
+ newBuildInfo.program = buildInfo.program;
+ // Update sourceFileInfo
+ var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
+ newBuildInfo.bundle.js.sources = js.sources;
+ if (dts) {
+ newBuildInfo.bundle.dts.sources = dts.sources;
+ }
+ newBuildInfo.bundle.sourceFiles = sourceFiles;
+ outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
+ return;
+ case declarationFilePath:
+ if (declarationText === text)
+ return;
+ break;
+ case declarationMapPath:
+ if (declarationMapText === text)
+ return;
+ break;
+ default:
+ ts.Debug.fail("Unexpected path: " + name);
+ }
+ outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
+ },
+ isEmitBlocked: ts.returnFalse,
+ readFile: function (f) { return host.readFile(f); },
+ fileExists: function (f) { return host.fileExists(f); },
+ directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }),
+ useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
+ getProgramBuildInfo: ts.returnUndefined
+ };
+ emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, /*emitOnlyDtsFiles*/ false, ts.getTransformers(config.options));
+ return outputFiles;
+ }
+ ts.emitUsingBuildInfo = emitUsingBuildInfo;
var PipelinePhase;
(function (PipelinePhase) {
PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
@@ -82252,6 +83556,10 @@
var ownWriter; // Reusable `EmitTextWriter` for basic printing.
var write = writeBase;
var isOwnFileEmit;
+ var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
+ var recordInternalSection = printerOptions.recordInternalSection;
+ var sourceFileTextPos = 0;
+ var sourceFileTextKind = "text" /* Text */;
// Source Maps
var sourceMapsDisabled = true;
var sourceMapGenerator;
@@ -82277,7 +83585,8 @@
writeNode: writeNode,
writeList: writeList,
writeFile: writeFile,
- writeBundle: writeBundle
+ writeBundle: writeBundle,
+ bundleFileInfo: bundleFileInfo
};
function printNode(hint, node, sourceFile) {
switch (hint) {
@@ -82292,9 +83601,9 @@
break;
}
switch (node.kind) {
- case 279 /* SourceFile */: return printFile(node);
- case 280 /* Bundle */: return printBundle(node);
- case 281 /* UnparsedSource */: return printUnparsedSource(node);
+ case 284 /* SourceFile */: return printFile(node);
+ case 285 /* Bundle */: return printBundle(node);
+ case 286 /* UnparsedSource */: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -82304,7 +83613,7 @@
return endPrint();
}
function printBundle(bundle) {
- writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined);
+ writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
return endPrint();
}
function printFile(sourceFile) {
@@ -82332,7 +83641,49 @@
reset();
writer = previousWriter;
}
- function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) {
+ function getTextPosWithWriteLine() {
+ return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
+ }
+ function updateOrPushBundleFileTextLike(pos, end, kind) {
+ var last = ts.lastOrUndefined(bundleFileInfo.sections);
+ if (last && last.kind === kind) {
+ last.end = end;
+ }
+ else {
+ bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
+ }
+ }
+ function recordBundleFileInternalSectionStart(node) {
+ if (recordInternalSection &&
+ bundleFileInfo &&
+ currentSourceFile &&
+ (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
+ ts.isInternalDeclaration(node, currentSourceFile) &&
+ sourceFileTextKind !== "internal" /* Internal */) {
+ var prevSourceFileTextKind = sourceFileTextKind;
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = "internal" /* Internal */;
+ return prevSourceFileTextKind;
+ }
+ return undefined;
+ }
+ function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
+ if (prevSourceFileTextKind) {
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = prevSourceFileTextKind;
+ }
+ }
+ function recordBundleFileTextLikeSection(end) {
+ if (sourceFileTextPos < end) {
+ updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
+ return true;
+ }
+ return false;
+ }
+ function writeBundle(bundle, output, sourceMapGenerator) {
+ var _a;
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output, sourceMapGenerator);
@@ -82340,18 +83691,49 @@
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
- var prepend = _b[_a];
+ for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
+ var prepend = _c[_b];
writeLine();
+ var pos = writer.getTextPos();
+ var savedSections = bundleFileInfo && bundleFileInfo.sections;
+ if (savedSections)
+ bundleFileInfo.sections = [];
print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
+ if (bundleFileInfo) {
+ var newSections = bundleFileInfo.sections;
+ bundleFileInfo.sections = savedSections;
+ if (prepend.oldFileOfCurrentEmit)
+ (_a = bundleFileInfo.sections).push.apply(_a, newSections);
+ else {
+ newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prepend" /* Prepend */, data: prepend.fileName, texts: newSections });
}
- if (bundleInfo) {
- bundleInfo.originalOffset = writer.getTextPos();
}
- for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
- var sourceFile = _d[_c];
+ }
+ sourceFileTextPos = getTextPosWithWriteLine();
+ for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
+ var sourceFile = _e[_d];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
+ if (bundleFileInfo && bundle.sourceFiles.length) {
+ var end = writer.getTextPos();
+ if (recordBundleFileTextLikeSection(end)) {
+ // Store prologues
+ var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
+ if (prologues) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.prologues = prologues;
+ }
+ // Store helpes
+ var helpers = getHelpersFromBundledSourceFiles(bundle);
+ if (helpers) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.helpers = helpers;
+ }
+ }
+ }
reset();
writer = previousWriter;
}
@@ -82421,8 +83803,10 @@
function emit(node) {
if (node === undefined)
return;
+ var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
pipelinePhase(4 /* Unspecified */, node);
+ recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
}
function emitIdentifierName(node) {
if (node === undefined)
@@ -82449,12 +83833,12 @@
}
// falls through
case 2 /* Comments */:
- if (!commentsDisabled && node.kind !== 279 /* SourceFile */) {
+ if (!commentsDisabled && node.kind !== 284 /* SourceFile */) {
return pipelineEmitWithComments;
}
// falls through
case 3 /* SourceMaps */:
- if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) {
+ if (!sourceMapsDisabled && node.kind !== 284 /* SourceFile */ && !ts.isInJsonFile(node)) {
return pipelineEmitWithSourceMap;
}
// falls through
@@ -82491,8 +83875,16 @@
case 16 /* TemplateMiddle */:
case 17 /* TemplateTail */:
return emitLiteral(node);
- case 281 /* UnparsedSource */:
- return emitUnparsedSource(node);
+ case 286 /* UnparsedSource */:
+ case 280 /* UnparsedPrepend */:
+ return emitUnparsedSourceOrPrepend(node);
+ case 279 /* UnparsedPrologue */:
+ return writeUnparsedNode(node);
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return emitUnparsedTextLike(node);
+ case 283 /* UnparsedSyntheticReference */:
+ return emitUnparsedSyntheticReference(node);
// Identifiers
case 72 /* Identifier */:
return emitIdentifier(node);
@@ -82536,7 +83928,7 @@
return emitTypeReference(node);
case 165 /* FunctionType */:
return emitFunctionType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return emitJSDocFunctionType(node);
case 166 /* ConstructorType */:
return emitConstructorType(node);
@@ -82574,20 +83966,20 @@
return emitLiteralType(node);
case 183 /* ImportType */:
return emitImportTypeNode(node);
- case 284 /* JSDocAllType */:
+ case 289 /* JSDocAllType */:
writePunctuation("*");
return;
- case 285 /* JSDocUnknownType */:
+ case 290 /* JSDocUnknownType */:
writePunctuation("?");
return;
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return emitJSDocNullableType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return emitJSDocNonNullableType(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return emitJSDocOptionalType(node);
case 172 /* RestType */:
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return emitRestOrJSDocVariadicType(node);
// Binding patterns
case 184 /* ObjectBindingPattern */:
@@ -82725,30 +84117,30 @@
case 278 /* EnumMember */:
return emitEnumMember(node);
// JSDoc nodes (only used in codefixes currently)
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return emitJSDocPropertyLikeTag(node);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return emitJSDocSimpleTypedTag(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return emitJSDocAugmentsTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return emitJSDocTemplateTag(node);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return emitJSDocTypedefTag(node);
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return emitJSDocCallbackTag(node);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return emitJSDocSignature(node);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return emitJSDocTypeLiteral(node);
- case 296 /* JSDocClassTag */:
- case 294 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
return emitJSDocSimpleTag(node);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return emitJSDoc(node);
// Transformation nodes (ignored)
}
@@ -82847,9 +84239,9 @@
case 264 /* JsxFragment */:
return emitJsxFragment(node);
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return emitPartiallyEmittedExpression(node);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return emitCommaList(node);
}
}
@@ -82865,22 +84257,45 @@
var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node);
pipelinePhase(hint, substituteNode(hint, node));
}
+ function getHelpersFromBundledSourceFiles(bundle) {
+ var result;
+ if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
+ return undefined;
+ }
+ var bundledHelpers = ts.createMap();
+ for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
+ var helpers = getSortedEmitHelpers(sourceFile);
+ if (!helpers)
+ continue;
+ for (var _c = 0, helpers_3 = helpers; _c < helpers_3.length; _c++) {
+ var helper = helpers_3[_c];
+ if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
+ bundledHelpers.set(helper.name, true);
+ (result || (result = [])).push(helper.name);
+ }
+ }
+ }
+ return result;
+ }
function emitHelpers(node) {
var helpersEmitted = false;
- var bundle = node.kind === 280 /* Bundle */ ? node : undefined;
+ var bundle = node.kind === 285 /* Bundle */ ? node : undefined;
if (bundle && moduleKind === ts.ModuleKind.None) {
return;
}
- var numNodes = bundle ? bundle.sourceFiles.length : 1;
+ var numPrepends = bundle ? bundle.prepends.length : 0;
+ var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
for (var i = 0; i < numNodes; i++) {
- var currentNode = bundle ? bundle.sourceFiles[i] : node;
- var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile;
- var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined;
- var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit;
- var helpers = ts.getEmitHelpers(currentNode);
+ var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
+ var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
+ var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
+ var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
+ var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
if (helpers) {
- for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
- var helper = _b[_a];
+ for (var _a = 0, helpers_4 = helpers; _a < helpers_4.length; _a++) {
+ var helper = helpers_4[_a];
if (!helper.scoped) {
// Skip the helper if it can be skipped and the noEmitHelpers compiler
// option is set, or if it can be imported and the importHelpers compiler
@@ -82900,18 +84315,25 @@
// Skip the helper if it is scoped and we are emitting bundled helpers
continue;
}
+ var pos = getTextPosWithWriteLine();
if (typeof helper.text === "string") {
writeLines(helper.text);
}
else {
writeLines(helper.text(makeFileLevelOptimisticUniqueName));
}
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
helpersEmitted = true;
}
}
}
return helpersEmitted;
}
+ function getSortedEmitHelpers(node) {
+ var helpers = ts.getEmitHelpers(node);
+ return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
+ }
//
// Literals/Pseudo-literals
//
@@ -82938,8 +84360,42 @@
}
}
// SyntaxKind.UnparsedSource
- function emitUnparsedSource(unparsed) {
- writer.rawWrite(unparsed.text);
+ // SyntaxKind.UnparsedPrepend
+ function emitUnparsedSourceOrPrepend(unparsed) {
+ for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
+ var text = _b[_a];
+ writeLine();
+ emit(text);
+ }
+ }
+ // SyntaxKind.UnparsedPrologue
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ // SyntaxKind.UnparsedSyntheticReference
+ function writeUnparsedNode(unparsed) {
+ writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
+ }
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ function emitUnparsedTextLike(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 281 /* UnparsedText */ ?
+ "text" /* Text */ :
+ "internal" /* Internal */);
+ }
+ }
+ // SyntaxKind.UnparsedSyntheticReference
+ function emitUnparsedSyntheticReference(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ var section = ts.clone(unparsed.section);
+ section.pos = pos;
+ section.end = writer.getTextPos();
+ bundleFileInfo.sections.push(section);
+ }
}
//
// Identifiers
@@ -82994,7 +84450,7 @@
emit(node.dotDotDotToken);
emitNodeWithWriter(node.name, writeParameter);
emit(node.questionToken);
- if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) {
+ if (node.parent && node.parent.kind === 294 /* JSDocFunctionType */ && !node.name) {
emit(node.type);
}
else {
@@ -83874,7 +85330,7 @@
}
function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
// Emit all the prologue directives (like "use strict").
- var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true);
+ var statementOffset = emitPrologueDirectives(body.statements);
var pos = writer.getTextPos();
emitHelpers(body);
if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
@@ -84134,7 +85590,7 @@
writePunctuation(">");
}
function emitJsxText(node) {
- writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true));
+ writer.writeLiteral(node.text);
}
function emitJsxClosingElementOrFragment(node) {
writePunctuation("</");
@@ -84279,7 +85735,7 @@
}
}
if (node.tags) {
- if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) {
+ if (node.tags.length === 1 && node.tags[0].kind === 307 /* JSDocTypeTag */ && !node.comment) {
writeSpace();
emit(node.tags[0]);
}
@@ -84313,7 +85769,7 @@
function emitJSDocTypedefTag(tag) {
emitJSDocTagName(tag.tagName);
if (tag.typeExpression) {
- if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
emitJSDocTypeExpression(tag.typeExpression);
}
else {
@@ -84332,7 +85788,7 @@
emit(tag.fullName);
}
emitJSDocComment(tag.comment);
- if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) {
+ if (tag.typeExpression && tag.typeExpression.kind === 297 /* JSDocTypeLiteral */) {
emitJSDocTypeLiteral(tag.typeExpression);
}
}
@@ -84419,6 +85875,16 @@
}
function emitSyntheticTripleSlashReferencesIfNeeded(node) {
emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
+ for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
+ for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
+ var ref = _d[_c];
+ emit(ref);
+ writeLine();
+ }
+ }
+ }
}
function emitTripleSlashDirectivesIfNeeded(node) {
if (node.isDeclarationFile)
@@ -84426,7 +85892,10 @@
}
function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
if (hasNoDefaultLib) {
+ var pos = writer.getTextPos();
writeComment("/// <reference no-default-lib=\"true\"/>");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
writeLine();
}
if (currentSourceFile && currentSourceFile.moduleName) {
@@ -84447,17 +85916,26 @@
}
for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
var directive = files_1[_c];
+ var pos = writer.getTextPos();
writeComment("/// <reference path=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
writeLine();
}
- for (var _d = 0, types_18 = types; _d < types_18.length; _d++) {
- var directive = types_18[_d];
+ for (var _d = 0, types_19 = types; _d < types_19.length; _d++) {
+ var directive = types_19[_d];
+ var pos = writer.getTextPos();
writeComment("/// <reference types=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
writeLine();
}
for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
var directive = libs_1[_e];
+ var pos = writer.getTextPos();
writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
writeLine();
}
}
@@ -84482,16 +85960,22 @@
* Emits any prologue directives at the start of a Statement list, returning the
* number of prologue directives written to the output.
*/
- function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) {
+ function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
+ var needsToSetSourceFile = !!sourceFile;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (ts.isPrologueDirective(statement)) {
var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
if (shouldEmitPrologueDirective) {
- if (startWithNewLine || i > 0) {
- writeLine();
+ if (needsToSetSourceFile) {
+ needsToSetSourceFile = false;
+ setSourceFile(sourceFile);
}
+ writeLine();
+ var pos = writer.getTextPos();
emit(statement);
+ if (recordBundleFileSection && bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
if (seenPrologueDirectives) {
seenPrologueDirectives.set(statement.expression.text, true);
}
@@ -84504,23 +85988,70 @@
}
return statements.length;
}
+ function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
+ for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
+ var prologue = prologues_1[_a];
+ if (!seenPrologueDirectives.has(prologue.data)) {
+ writeLine();
+ var pos = writer.getTextPos();
+ emit(prologue);
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
+ if (seenPrologueDirectives) {
+ seenPrologueDirectives.set(prologue.data, true);
+ }
+ }
+ }
+ }
function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
if (ts.isSourceFile(sourceFileOrBundle)) {
- setSourceFile(sourceFileOrBundle);
- emitPrologueDirectives(sourceFileOrBundle.statements);
+ emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
}
else {
var seenPrologueDirectives = ts.createMap();
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
- setSourceFile(sourceFile);
- emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
+ emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
}
setSourceFile(undefined);
}
}
+ function getPrologueDirectivesFromBundledSourceFiles(bundle) {
+ var seenPrologueDirectives = ts.createMap();
+ var prologues;
+ for (var index = 0; index < bundle.sourceFiles.length; index++) {
+ var sourceFile = bundle.sourceFiles[index];
+ var directives = void 0;
+ var end = 0;
+ for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
+ var statement = _b[_a];
+ if (!ts.isPrologueDirective(statement))
+ break;
+ if (seenPrologueDirectives.has(statement.expression.text))
+ continue;
+ seenPrologueDirectives.set(statement.expression.text, true);
+ (directives || (directives = [])).push({
+ pos: statement.pos,
+ end: statement.end,
+ expression: {
+ pos: statement.expression.pos,
+ end: statement.expression.end,
+ text: statement.expression.text
+ }
+ });
+ end = end < statement.end ? statement.end : end;
+ }
+ if (directives)
+ (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
+ }
+ return prologues;
+ }
function emitShebangIfNeeded(sourceFileOrBundle) {
- if (ts.isSourceFile(sourceFileOrBundle)) {
+ if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
var shebang = ts.getShebang(sourceFileOrBundle.text);
if (shebang) {
writeComment(shebang);
@@ -84529,11 +86060,18 @@
}
}
else {
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ ts.Debug.assertNode(prepend, ts.isUnparsedSource);
+ if (emitShebangIfNeeded(prepend)) {
+ return true;
+ }
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
// Emit only the first encountered shebang
if (emitShebangIfNeeded(sourceFile)) {
- break;
+ return true;
}
}
}
@@ -84736,6 +86274,7 @@
}
// Emit each child.
var previousSibling = void 0;
+ var previousSourceFileTextKind = void 0;
var shouldDecreaseIndentAfterEmit = false;
for (var i = 0; i < count; i++) {
var child = children[start + i];
@@ -84756,6 +86295,7 @@
emitLeadingCommentsOfPosition(previousSibling.end);
}
writeDelimiter(format);
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write either a line terminator or whitespace to separate the elements.
if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
// If a synthesized node in a single-line list starts on a new
@@ -84772,6 +86312,7 @@
}
}
// Emit this child.
+ previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
if (shouldEmitInterveningComments) {
if (emitTrailingCommentsOfPosition) {
var commentRange = ts.getCommentRange(child);
@@ -84806,6 +86347,7 @@
if (format & 128 /* Indented */) {
decreaseIndent();
}
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write the closing line terminator or closing whitespace.
if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
writeLine();
@@ -84907,7 +86449,6 @@
if (line.length) {
writeLine();
write(line);
- writer.rawWrite(newLine);
}
}
}
@@ -85421,7 +86962,7 @@
hasWrittenComment = false;
var emitFlags = ts.getEmitFlags(node);
var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
- var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 312 /* 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 === 11 /* JsxText */;
@@ -85681,19 +87222,28 @@
return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
}
// Source Maps
+ function getParsedSourceMap(node) {
+ if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
+ node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
+ }
+ return node.parsedSourceMap || undefined;
+ }
function pipelineEmitWithSourceMap(hint, node) {
var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node);
- if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) {
- var parsed = ts.tryParseRawSourceMap(node.sourceMapText);
- if (parsed) {
- sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath);
+ if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
+ pipelinePhase(hint, node);
+ }
+ else if (ts.isUnparsedNode(node)) {
+ var parsed = getParsedSourceMap(node.parent);
+ if (parsed && sourceMapGenerator) {
+ sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
}
pipelinePhase(hint, node);
}
else {
var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
var emitFlags = ts.getEmitFlags(node);
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitSourcePos(source, skipSourceTrivia(source, pos));
@@ -85706,7 +87256,7 @@
else {
pipelinePhase(hint, node);
}
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitSourcePos(source, end);
@@ -85834,7 +87384,8 @@
writeFile: host.writeFile && writeFile,
addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
addOrDeleteFile: addOrDeleteFile,
- clearCache: clearCache
+ clearCache: clearCache,
+ realpath: host.realpath && realpath
};
function toPath(fileName) {
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
@@ -85931,7 +87482,7 @@
var rootDirPath = toPath(rootDir);
var result = tryReadDirectory(rootDir, rootDirPath);
if (result) {
- return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries);
+ return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
}
return host.readDirectory(rootDir, extensions, excludes, includes, depth);
function getFileSystemEntries(dir) {
@@ -85942,6 +87493,9 @@
return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
}
}
+ function realpath(s) {
+ return host.realpath ? host.realpath(s) : s;
+ }
function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
if (existingResult) {
@@ -86212,11 +87766,7 @@
function createCompilerHostWorker(options, setParentNodes, system) {
if (system === void 0) { system = ts.sys; }
var existingDirectories = ts.createMap();
- function getCanonicalFileName(fileName) {
- // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
- // otherwise use toLowerCase as a canonical form.
- return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
- }
+ var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
function getSourceFile(fileName, languageVersion, onError) {
var text;
try {
@@ -86341,20 +87891,21 @@
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
- return value || undefined;
+ return value !== false ? value : undefined;
return setReadFileCache(key, fileName);
};
var setReadFileCache = function (key, fileName) {
var newValue = originalReadFile.call(host, fileName);
- readFileCache.set(key, newValue || false);
+ readFileCache.set(key, newValue !== undefined ? newValue : false);
return newValue;
};
host.readFile = function (fileName) {
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
- return value; // could be .d.ts from output
- if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ return value !== false ? value : undefined; // could be .d.ts from output
+ // Cache json or buildInfo
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
return originalReadFile.call(host, fileName);
}
return setReadFileCache(key, fileName);
@@ -86385,7 +87936,7 @@
var key = toPath(fileName);
fileExistsCache.delete(key);
var value = readFileCache.get(key);
- if (value && value !== data) {
+ if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.delete(key);
}
@@ -86831,11 +88382,18 @@
if (rootNames.length) {
for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
var parsedRef = resolvedProjectReferences_1[_i];
- if (parsedRef) {
+ if (!parsedRef)
+ continue;
var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
if (out) {
- var dtsOutfile = ts.changeExtension(out, ".d.ts");
- processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ }
+ else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
+ for (var _a = 0, _b = parsedRef.commandLine.fileNames; _a < _b.length; _a++) {
+ var fileName = _b[_a];
+ if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(fileName)) {
+ processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ }
}
}
}
@@ -86883,8 +88441,8 @@
// not part of the new program.
if (oldProgram && host.onReleaseOldSourceFile) {
var oldSourceFiles = oldProgram.getSourceFiles();
- for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) {
- var oldSourceFile = oldSourceFiles_1[_a];
+ for (var _c = 0, oldSourceFiles_1 = oldSourceFiles; _c < oldSourceFiles_1.length; _c++) {
+ var oldSourceFile = oldSourceFiles_1[_c];
var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
if (shouldCreateNewSourceFile || !newFile ||
// old file wasnt redirect but new file is
@@ -86940,7 +88498,8 @@
getProjectReferenceRedirect: getProjectReferenceRedirect,
getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
- forEachResolvedProjectReference: forEachResolvedProjectReference
+ forEachResolvedProjectReference: forEachResolvedProjectReference,
+ emitBuildInfo: emitBuildInfo
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -86969,7 +88528,7 @@
}
function getCommonSourceDirectory() {
if (commonSourceDirectory === undefined) {
- var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); });
+ var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
// If a rootDir is specified use it as the commonSourceDirectory
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
@@ -87358,7 +88917,8 @@
}
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, getLibFileFromReference: program.getLibFileFromReference, 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) {
+ 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, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
+ getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, 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))
@@ -87367,7 +88927,20 @@
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(); } });
+ } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); } });
+ }
+ function emitBuildInfo(writeFileCallback) {
+ ts.Debug.assert(!options.out && !options.outFile);
+ ts.performance.mark("beforeEmit");
+ var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback),
+ /*targetSourceFile*/ undefined,
+ /*emitOnlyDtsFiles*/ false,
+ /*transformers*/ undefined,
+ /*declaraitonTransformers*/ undefined,
+ /*onlyBuildInfo*/ true);
+ ts.performance.mark("afterEmit");
+ ts.performance.measure("Emit", "beforeEmit", "afterEmit");
+ return emitResult;
}
function getResolvedProjectReferences() {
return resolvedProjectReferences;
@@ -87376,28 +88949,11 @@
return projectReferences;
}
function getPrependNodes() {
- if (!projectReferences) {
- return ts.emptyArray;
- }
- var nodes = [];
- for (var i = 0; i < projectReferences.length; i++) {
- var ref = projectReferences[i];
- var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
- if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
- var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
- // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
- if (!out)
- continue;
- var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- var node = ts.createInputFiles(function (fileName) {
+ return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
var path = toPath(fileName);
var sourceFile = getSourceFileByPath(path);
return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
- }, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath);
- nodes.push(node);
- }
- }
- return nodes;
+ });
}
function isSourceFileFromExternalLibrary(file) {
return !!sourceFilesFoundSearchingNodeModules.get(file.path);
@@ -87469,8 +89025,7 @@
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
ts.performance.mark("beforeEmit");
var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217
- emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -88082,7 +89637,6 @@
if (refFile) {
var redirect = getProjectReferenceRedirect(fileName);
if (redirect) {
- (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName);
fileName = redirect;
// Once we start redirecting to a file, we can potentially come back to it
// via a back-reference from another file in the .d.ts folder. If that happens we'll
@@ -88179,7 +89733,7 @@
var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
return out ?
ts.changeExtension(out, ".d.ts" /* Dts */) :
- ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine);
+ ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
}
/**
* Get the referenced project if the file is input file from that reference project
@@ -88472,18 +90026,29 @@
if (options.declaration === false) {
createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
}
+ if (options.incremental === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
+ }
+ }
+ if (options.tsBuildInfoFile) {
+ if (!ts.isIncrementalCompilation(options)) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
+ }
}
verifyProjectReferences();
// List of collected files is complete; validate exhautiveness if this is a project with a file list
if (options.composite) {
- var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; });
- if (rootNames.length < sourceFiles.length) {
- var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); });
- for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) {
- var file = _a[_i];
- if (normalizedRootNames.indexOf(file) === -1) {
- 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));
- }
+ var rootPaths = rootNames.map(toPath);
+ for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
+ var file = files_3[_i];
+ // Ignore declaration files
+ if (file.isDeclarationFile)
+ continue;
+ // Ignore json file thats from project reference
+ if (ts.isJsonSourceFile(file) && getResolvedProjectReferenceToRedirect(file.fileName))
+ continue;
+ if (rootPaths.indexOf(file.path) === -1) {
+ 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.fileName));
}
}
}
@@ -88666,6 +90231,7 @@
}
}
function verifyProjectReferences() {
+ var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getOutputPathForBuildInfo(options) : undefined;
forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
var parentFile = parent && parent.sourceFile;
@@ -88692,6 +90258,10 @@
createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
}
}
+ if (!parent && buildInfoPath && buildInfoPath === ts.getOutputPathForBuildInfo(options)) {
+ createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
+ hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
+ }
});
}
function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
@@ -88836,11 +90406,32 @@
readFile: function (f) { return directoryStructureHost.readFile(f); },
useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
getCurrentDirectory: function () { return host.getCurrentDirectory(); },
- onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || (function () { return undefined; }),
+ onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
trace: host.trace ? function (s) { return host.trace(s); } : undefined
};
}
ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
+ /* @internal */
+ function createPrependNodes(projectReferences, getCommandLine, readFile) {
+ if (!projectReferences)
+ return ts.emptyArray;
+ var nodes;
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = getCommandLine(ref, i);
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!out)
+ continue;
+ var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
+ (nodes || (nodes = [])).push(node);
+ }
+ }
+ return nodes || ts.emptyArray;
+ }
+ ts.createPrependNodes = createPrependNodes;
function resolveProjectReferencePath(hostOrRef, ref) {
var passedInRef = ref ? ref : hostOrRef;
return ts.resolveConfigFileProjectName(passedInRef.path);
@@ -89037,7 +90628,7 @@
// Create the reference map, and set the file infos
for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
- var version_1 = sourceFile.version;
+ var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined;
if (referencedMap) {
var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
@@ -89092,9 +90683,9 @@
*/
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
+ // They will be committed once it is safe to use them
// eg when calling this api from tsserver, if there is no cancellation of the operation
- // In the other cases the affected files signatures are commited only after the iteration through the result is complete
+ // In the other cases the affected files signatures are committed only after the iteration through the result is complete
var signatureCache = cacheToUpdateSignature || ts.createMap();
var sourceFile = programOfThisState.getSourceFileByPath(path);
if (!sourceFile) {
@@ -89384,11 +90975,14 @@
var affectedSignatures = oldState.currentAffectedFilesSignatures;
ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
}
+ var changedFilesSet = oldState.changedFilesSet;
if (canCopySemanticDiagnostics) {
- ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
+ ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
}
// Copy old state's changed files set
- ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet);
+ if (changedFilesSet) {
+ ts.copyEntries(changedFilesSet, state.changedFilesSet);
+ }
if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit;
state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
@@ -89426,7 +91020,7 @@
// Unchanged file copy diagnostics
var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
if (diagnostics) {
- state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics);
+ state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics);
if (!state.semanticDiagnosticsFromOldState) {
state.semanticDiagnosticsFromOldState = ts.createMap();
}
@@ -89434,8 +91028,45 @@
}
}
});
+ if (oldCompilerOptions &&
+ (oldCompilerOptions.outDir !== compilerOptions.outDir ||
+ oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
+ (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
+ // Add all files to affectedFilesPendingEmit since emit changed
+ state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(function (f) { return f.path; }));
+ if (state.affectedFilesPendingEmitIndex === undefined) {
+ state.affectedFilesPendingEmitIndex = 0;
+ }
+ ts.Debug.assert(state.seenAffectedFiles === undefined);
+ state.seenAffectedFiles = ts.createMap();
+ }
return state;
}
+ function convertToDiagnostics(diagnostics, newProgram) {
+ if (!diagnostics.length)
+ return ts.emptyArray;
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToDiagnosticRelatedInformation(diagnostic, newProgram) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && newProgram.getSourceFileByPath(file), messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToDiagnosticMessageChain(messageText, newProgram) });
+ }
+ function convertToDiagnosticMessageChain(diagnostic, newProgram) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram) });
+ }
/**
* Releases program and other related not needed properties
*/
@@ -89655,8 +91286,11 @@
* 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
*/
- function doneWithAffectedFile(state, affected, isPendingEmit) {
- if (affected === state.program) {
+ function doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit) {
+ if (isBuildInfoEmit) {
+ state.emittedBuildInfo = true;
+ }
+ else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
@@ -89673,8 +91307,8 @@
/**
* Returns the result with affected file
*/
- function toAffectedFileResult(state, result, affected, isPendingEmit) {
- doneWithAffectedFile(state, affected, isPendingEmit);
+ function toAffectedFileResult(state, result, affected, isPendingEmit, isBuildInfoEmit) {
+ doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
return { result: result, affected: affected };
}
/**
@@ -89697,6 +91331,77 @@
}
return diagnostics;
}
+ /**
+ * Gets the program information to be emitted in buildInfo so that we can use it to create new program
+ */
+ function getProgramBuildInfo(state) {
+ if (state.compilerOptions.outFile || state.compilerOptions.out)
+ return undefined;
+ var fileInfos = {};
+ state.fileInfos.forEach(function (value, key) {
+ var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
+ fileInfos[key] = signature === undefined ? value : { version: value.version, signature: signature };
+ });
+ var result = { fileInfos: fileInfos, options: state.compilerOptions };
+ if (state.referencedMap) {
+ var referencedMap_1 = {};
+ state.referencedMap.forEach(function (value, key) {
+ referencedMap_1[key] = ts.arrayFrom(value.keys());
+ });
+ result.referencedMap = referencedMap_1;
+ }
+ if (state.exportedModulesMap) {
+ var exportedModulesMap_1 = {};
+ state.exportedModulesMap.forEach(function (value, key) {
+ var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
+ // Not in temporary cache, use existing value
+ if (newValue === undefined)
+ exportedModulesMap_1[key] = ts.arrayFrom(value.keys());
+ // Value in cache and has updated value map, use that
+ else if (newValue)
+ exportedModulesMap_1[key] = ts.arrayFrom(newValue.keys());
+ });
+ result.exportedModulesMap = exportedModulesMap_1;
+ }
+ if (state.semanticDiagnosticsPerFile) {
+ var semanticDiagnosticsPerFile_1 = [];
+ // Currently not recording actual errors since those mean no emit for tsc --build
+ state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ?
+ [
+ key,
+ state.hasReusableDiagnostic ?
+ value :
+ convertToReusableDiagnostics(value)
+ ] :
+ key); });
+ result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1;
+ }
+ return result;
+ }
+ function convertToReusableDiagnostics(diagnostics) {
+ ts.Debug.assert(!!diagnostics.length);
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToReusableDiagnosticRelatedInformation(diagnostic);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToReusableDiagnosticRelatedInformation(diagnostic) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && file.path, messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToReusableDiagnosticMessageChain(messageText) });
+ }
+ function convertToReusableDiagnosticMessageChain(diagnostic) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next) });
+ }
var BuilderProgramKind;
(function (BuilderProgramKind) {
BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
@@ -89753,6 +91458,7 @@
var computeHash = host.createHash || ts.generateDjb2Hash;
var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
var backupState;
+ newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state); };
// To ensure that we arent storing any references to old program or new program without state
newProgram = undefined; // TODO: GH#18217
oldProgram = undefined;
@@ -89796,8 +91502,17 @@
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
affected = getNextAffectedFilePendingEmit(state);
if (!affected) {
+ if (state.emittedBuildInfo) {
return undefined;
}
+ var affected_1 = ts.Debug.assertDefined(state.program);
+ return toAffectedFileResult(state,
+ // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
+ // Otherwise just affected file
+ affected_1.emitBuildInfo(writeFile || host.writeFile, cancellationToken), affected_1,
+ /*isPendingEmitFile*/ false,
+ /*isBuildInfoEmit*/ true);
+ }
isPendingEmitFile = true;
}
else {
@@ -89922,13 +91637,60 @@
}
var diagnostics;
for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
- var sourceFile_2 = _a[_i];
- diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken));
+ var sourceFile_1 = _a[_i];
+ diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
}
return diagnostics || ts.emptyArray;
}
}
ts.createBuilderProgram = createBuilderProgram;
+ function getMapOfReferencedSet(mapLike) {
+ if (!mapLike)
+ return undefined;
+ var map = ts.createMap();
+ // Copies keys/values from template. Note that for..in will not throw if
+ // template is undefined, and instead will just exit the loop.
+ for (var key in mapLike) {
+ if (ts.hasProperty(mapLike, key)) {
+ map.set(key, ts.arrayToSet(mapLike[key]));
+ }
+ }
+ return map;
+ }
+ function createBuildProgramUsingProgramBuildInfo(program) {
+ var fileInfos = ts.createMapFromTemplate(program.fileInfos);
+ var state = {
+ fileInfos: fileInfos,
+ compilerOptions: program.options,
+ referencedMap: getMapOfReferencedSet(program.referencedMap),
+ exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
+ semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return ts.isString(value) ? value : value[0]; }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
+ hasReusableDiagnostic: true
+ };
+ return {
+ getState: function () { return state; },
+ backupState: ts.noop,
+ restoreState: ts.noop,
+ getProgram: ts.notImplemented,
+ getProgramOrUndefined: ts.returnUndefined,
+ releaseProgram: ts.noop,
+ getCompilerOptions: function () { return state.compilerOptions; },
+ getSourceFile: ts.notImplemented,
+ getSourceFiles: ts.notImplemented,
+ getOptionsDiagnostics: ts.notImplemented,
+ getGlobalDiagnostics: ts.notImplemented,
+ getConfigFileParsingDiagnostics: ts.notImplemented,
+ getSyntacticDiagnostics: ts.notImplemented,
+ getDeclarationDiagnostics: ts.notImplemented,
+ getSemanticDiagnostics: ts.notImplemented,
+ emit: ts.notImplemented,
+ getAllDependencies: ts.notImplemented,
+ getCurrentDirectory: ts.notImplemented,
+ emitNextAffectedFile: ts.notImplemented,
+ getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
+ };
+ }
+ ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
return {
getState: ts.notImplemented,
@@ -89948,7 +91710,7 @@
getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
getAllDependencies: ts.notImplemented,
- getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); }
+ getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
};
function getProgram() {
return ts.Debug.assertDefined(state.program);
@@ -89974,10 +91736,10 @@
/*@internal*/
var ts;
(function (ts) {
- function isPathInNodeModulesStartingWithDot(path) {
- return ts.stringContains(path, "/node_modules/.");
+ function isPathIgnored(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); });
}
- ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot;
+ ts.isPathIgnored = isPathIgnored;
ts.maxNumberOfFilesToIterateForInvalidation = 256;
function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
var filesWithChangedSetOfUnresolvedImports;
@@ -90499,7 +92261,7 @@
}
else {
// If something to do with folder/file starting with "." in node_modules folder, skip it
- if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (isPathIgnored(fileOrDirectoryPath))
return false;
// Some file or directory in the watching directory is created
// Return early if it does not have any of the watching extension or not the custom failed lookup path
@@ -90976,6 +92738,8 @@
case ".jsx" /* Jsx */:
case ".json" /* Json */:
return ext;
+ case ".tsbuildinfo" /* TsBuildInfo */:
+ return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
default:
return ts.Debug.assertNever(ext);
}
@@ -91096,22 +92860,18 @@
var diagnostics = program.getConfigFileParsingDiagnostics().slice();
var configFileParsingDiagnosticsLength = diagnostics.length;
ts.addRange(diagnostics, program.getSyntacticDiagnostics());
- var reportSemanticDiagnostics = false;
// If we didn't have any syntactic errors, then also try getting the global and
// semantic errors.
if (diagnostics.length === configFileParsingDiagnosticsLength) {
ts.addRange(diagnostics, program.getOptionsDiagnostics());
ts.addRange(diagnostics, program.getGlobalDiagnostics());
if (diagnostics.length === configFileParsingDiagnosticsLength) {
- reportSemanticDiagnostics = true;
+ ts.addRange(diagnostics, program.getSemanticDiagnostics());
}
}
// Emit and report any errors we ran into.
var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics;
ts.addRange(diagnostics, emitDiagnostics);
- if (reportSemanticDiagnostics) {
- ts.addRange(diagnostics, program.getSemanticDiagnostics());
- }
ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic);
if (writeFileName) {
var currentDir_1 = program.getCurrentDirectory();
@@ -91232,6 +92992,22 @@
}
}
ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
+ function setGetSourceFileAsHashVersioned(compilerHost, host) {
+ var originalGetSourceFile = compilerHost.getSourceFile;
+ var computeHash = host.createHash || ts.generateDjb2Hash;
+ compilerHost.getSourceFile = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
+ if (result) {
+ result.version = computeHash.call(host, result.text);
+ }
+ return result;
+ };
+ }
+ ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
/**
* Creates the watch compiler host that can be extended with config file or root file names and options host
*/
@@ -91257,7 +93033,7 @@
writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
createHash: ts.maybeBind(system, system.createHash),
- createProgram: createProgram
+ createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
};
}
ts.createProgramHost = createProgramHost;
@@ -91267,7 +93043,7 @@
function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
var writeFileName = function (s) { return system.write(s + system.newLine); };
- var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram);
+ var result = createProgramHost(system, createProgram);
ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = function (builderProgram) {
var compilerOptions = builderProgram.getCompilerOptions();
@@ -91306,6 +93082,49 @@
return host;
}
ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
+ function readBuilderProgram(compilerOptions, readFile) {
+ if (compilerOptions.out || compilerOptions.outFile)
+ return undefined;
+ var buildInfoPath = ts.getOutputPathForBuildInfo(compilerOptions);
+ if (!buildInfoPath)
+ return undefined;
+ var content = readFile(buildInfoPath);
+ if (!content)
+ return undefined;
+ var buildInfo = ts.getBuildInfo(content);
+ if (buildInfo.version !== ts.version)
+ return undefined;
+ if (!buildInfo.program)
+ return undefined;
+ return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program);
+ }
+ ts.readBuilderProgram = readBuilderProgram;
+ function createIncrementalCompilerHost(options, system) {
+ if (system === void 0) { system = ts.sys; }
+ var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
+ host.createHash = ts.maybeBind(system, system.createHash);
+ setGetSourceFileAsHashVersioned(host, system);
+ ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
+ return host;
+ }
+ ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
+ function createIncrementalProgram(_a) {
+ var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
+ host = host || createIncrementalCompilerHost(options);
+ createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
+ var oldProgram = readBuilderProgram(options, function (path) { return host.readFile(path); });
+ return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
+ }
+ function performIncrementalCompilation(input) {
+ var system = input.system || ts.sys;
+ var host = input.host || (input.host = createIncrementalCompilerHost(input.options, system));
+ var builderProgram = createIncrementalProgram(input);
+ var exitStatus = emitFilesAndReportErrors(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined);
+ if (input.afterProgramEmitAndDiagnostics)
+ input.afterProgramEmitAndDiagnostics(builderProgram);
+ return exitStatus;
+ }
+ ts.performIncrementalCompilation = performIncrementalCompilation;
})(ts || (ts = {}));
(function (ts) {
function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) {
@@ -91317,7 +93136,6 @@
}
}
ts.createWatchCompilerHost = createWatchCompilerHost;
- var initialVersion = 1;
function createWatchProgram(host) {
var builderProgram;
var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
@@ -91358,10 +93176,12 @@
var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
+ var configFileWatcher;
if (configFileName) {
- watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */);
+ configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */);
}
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
+ ts.setGetSourceFileAsHashVersioned(compilerHost, host);
// Members for CompilerHost
var getNewSourceFile = compilerHost.getSourceFile;
compilerHost.getSourceFile = function (fileName) {
@@ -91402,21 +93222,43 @@
(function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) :
(function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
+ builderProgram = ts.readBuilderProgram(compilerOptions, function (path) { return compilerHost.readFile(path); });
synchronizeProgram();
// Update the wild card directory watch
watchConfigFileWildCardDirectories();
return configFileName ?
- { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } :
- { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames };
+ { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } :
+ { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close };
+ function close() {
+ resolutionCache.clear();
+ ts.clearMap(sourceFilesCache, function (value) {
+ if (value && value.fileWatcher) {
+ value.fileWatcher.close();
+ value.fileWatcher = undefined;
+ }
+ });
+ if (configFileWatcher) {
+ configFileWatcher.close();
+ configFileWatcher = undefined;
+ }
+ if (watchedWildcardDirectories) {
+ ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
+ watchedWildcardDirectories = undefined;
+ }
+ if (missingFilesMap) {
+ ts.clearMap(missingFilesMap, ts.closeFileWatcher);
+ missingFilesMap = undefined;
+ }
+ }
function getCurrentBuilderProgram() {
return builderProgram;
}
function getCurrentProgram() {
- return builderProgram && builderProgram.getProgram();
+ return builderProgram && builderProgram.getProgramOrUndefined();
}
function synchronizeProgram() {
writeLog("Synchronizing program");
- var program = getCurrentProgram();
+ var program = getCurrentBuilderProgram();
if (hasChangedCompilerOptions) {
newLine = updateNewLine();
if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
@@ -91432,19 +93274,19 @@
}
}
else {
- createNewProgram(program, hasInvalidatedResolution);
+ createNewProgram(hasInvalidatedResolution);
}
if (host.afterProgramCreate) {
host.afterProgramCreate(builderProgram);
}
return builderProgram;
}
- function createNewProgram(program, hasInvalidatedResolution) {
+ function createNewProgram(hasInvalidatedResolution) {
// Compile the program
writeLog("CreatingProgramWith::");
writeLog(" roots: " + JSON.stringify(rootFileNames));
writeLog(" options: " + JSON.stringify(compilerOptions));
- var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program;
+ var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
hasChangedCompilerOptions = false;
hasChangedConfigFileParsingErrors = false;
resolutionCache.startCachingPerDirectoryResolution();
@@ -91484,10 +93326,10 @@
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
}
function isFileMissingOnHost(hostSourceFile) {
- return typeof hostSourceFile === "number";
+ return typeof hostSourceFile === "boolean";
}
- function isFilePresentOnHost(hostSourceFile) {
- return !!hostSourceFile.sourceFile;
+ function isFilePresenceUnknownOnHost(hostSourceFile) {
+ return typeof hostSourceFile.version === "boolean";
}
function fileExists(fileName) {
var path = toPath(fileName);
@@ -91505,36 +93347,32 @@
return undefined;
}
// Create new source file if requested or the versions dont match
- if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) {
+ if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
if (hostSourceFile) {
- if (shouldCreateNewSourceFile) {
- hostSourceFile.version++;
- }
if (sourceFile) {
// Set the source file and create file watcher now that file was present on the disk
hostSourceFile.sourceFile = sourceFile;
- sourceFile.version = hostSourceFile.version.toString();
+ hostSourceFile.version = sourceFile.version;
if (!hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */);
}
}
else {
// There is no source file on host any more, close the watch, missing file paths will track it
- if (isFilePresentOnHost(hostSourceFile)) {
+ if (hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher.close();
}
- sourceFilesCache.set(path, hostSourceFile.version);
+ sourceFilesCache.set(path, false);
}
}
else {
if (sourceFile) {
- sourceFile.version = initialVersion.toString();
var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */);
- sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher });
+ sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
}
else {
- sourceFilesCache.set(path, initialVersion);
+ sourceFilesCache.set(path, false);
}
}
return sourceFile;
@@ -91546,16 +93384,16 @@
if (hostSourceFile !== undefined) {
if (isFileMissingOnHost(hostSourceFile)) {
// The next version, lets set it as presence unknown file
- sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 });
+ sourceFilesCache.set(path, { version: false });
}
else {
- hostSourceFile.version++;
+ hostSourceFile.version = false;
}
}
}
function getSourceVersion(path) {
var hostSourceFile = sourceFilesCache.get(path);
- return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString();
+ return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
}
function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
@@ -91563,7 +93401,7 @@
// remove the cached entry.
// Note we arent deleting entry if file became missing in new program or
// there was version update and new source file was created.
- if (hostSourceFileInfo) {
+ if (hostSourceFileInfo !== undefined) {
// record the missing file paths so they can be removed later if watchers arent tracking them
if (isFileMissingOnHost(hostSourceFileInfo)) {
(missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
@@ -91652,7 +93490,7 @@
function onSourceFileChange(fileName, eventKind, path) {
updateCachedSystemWithFile(fileName, path, eventKind);
// Update the source file cache
- if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) {
+ if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
resolutionCache.invalidateResolutionOfFile(path);
}
resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
@@ -91696,7 +93534,7 @@
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
nextSourceFileVersion(fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
// 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
@@ -91750,16 +93588,23 @@
* This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
*/
UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
- UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream";
- UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate";
- UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked";
- UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream";
+ /**
+ * The project appears out of date because its upstream inputs are newer than its outputs,
+ * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
+ * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
+ */
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
+ UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
+ UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
+ UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
+ UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
+ UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
/**
* Projects with no outputs (i.e. "solution" files)
*/
- UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly";
+ UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
})(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
function createFileMap(toPath) {
// tslint:disable-next-line:no-null-keyword
@@ -91807,61 +93652,6 @@
function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
}
- 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);
- return ts.changeExtension(outputPath, ".d.ts" /* Dts */);
- }
- ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
- function getOutputJSFileName(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);
- 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) {
- // 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 = [];
- var js = getOutputJSFileName(inputFileName, configFile);
- outputs.push(js);
- if (configFile.options.sourceMap) {
- outputs.push(js + ".map");
- }
- 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");
- }
- }
- return outputs;
- }
- function getOutFileOutputs(project) {
- var out = project.options.outFile || project.options.out;
- if (!out) {
- return ts.Debug.fail("outFile must be set");
- }
- var outputs = [];
- outputs.push(out);
- if (project.options.sourceMap) {
- outputs.push(out + ".map");
- }
- if (ts.getEmitDeclarations(project.options)) {
- var dts = ts.changeExtension(out, ".d.ts" /* Dts */);
- outputs.push(dts);
- if (project.options.declarationMap) {
- outputs.push(dts + ".map");
- }
- }
- return outputs;
- }
- function rootDirOfOptions(opts, configFileName) {
- return opts.rootDir || ts.getDirectoryPath(configFileName);
- }
function newer(date1, date2) {
return date2 > date1 ? date2 : date1;
}
@@ -91881,7 +93671,7 @@
ts.createBuilderStatusReporter = createBuilderStatusReporter;
function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
var host = ts.createProgramHost(system, createProgram);
- host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; };
+ host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
@@ -91890,14 +93680,14 @@
}
function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
host.reportErrorSummary = reportErrorSummary;
return host;
}
ts.createSolutionBuilderHost = createSolutionBuilderHost;
function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
var watchHost = ts.createWatchHost(system, reportWatchStatus);
ts.copyProperties(host, watchHost);
return host;
@@ -91929,9 +93719,8 @@
var readFileWithCache = function (f) { return host.readFile(f); };
var projectCompilerOptions = baseCompilerOptions;
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; });
- var originalGetSourceFile = compilerHost.getSourceFile;
- var computeHash = host.createHash || ts.generateDjb2Hash;
- updateGetSourceFile();
+ ts.setGetSourceFileAsHashVersioned(compilerHost, host);
+ var buildInfoChecked = createFileMap(toPath);
// Watch state
var builderPrograms = createFileMap(toPath);
var diagnostics = createFileMap(toPath);
@@ -91969,6 +93758,7 @@
projectStatus.clear();
missingRoots.clear();
globalDependencyGraph = undefined;
+ buildInfoChecked.clear();
diagnostics.clear();
projectPendingBuild.clear();
projectErrorsReported.clear();
@@ -91983,29 +93773,6 @@
ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); });
ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher);
builderPrograms.clear();
- updateGetSourceFile();
- }
- function updateGetSourceFile() {
- if (options.watch) {
- if (compilerHost.getSourceFile === originalGetSourceFile) {
- compilerHost.getSourceFile = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
- if (result && options.watch) {
- result.version = computeHash.call(host, result.text);
- }
- return result;
- };
- }
- }
- else {
- if (compilerHost.getSourceFile !== originalGetSourceFile) {
- compilerHost.getSourceFile = originalGetSourceFile;
- }
- }
}
function isParsedCommandLine(entry) {
return !!entry.options;
@@ -92156,13 +93923,14 @@
newestInputFileTime = inputTime;
}
}
- // Collect the expected outputs of this project
- var outputs = getAllProjectOutputs(project);
- if (outputs.length === 0) {
+ // Container if no files are specified in the project
+ if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) {
return {
type: UpToDateStatusType.ContainerOnly
};
}
+ // Collect the expected outputs of this project
+ var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
// Now see if all outputs are newer than the newest input
var oldestOutputFileName = "(none)";
var oldestOutputFileTime = maximumDate;
@@ -92237,6 +94005,8 @@
upstreamProjectName: ref.path
};
}
+ // Check oldest output file name only if there is no missing output file name
+ if (!missingOutputFileName) {
// 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) {
@@ -92258,6 +94028,7 @@
};
}
}
+ }
if (missingOutputFileName !== undefined) {
return {
type: UpToDateStatusType.OutputMissing,
@@ -92271,9 +94042,33 @@
newerInputFileName: newestInputFileName
};
}
+ else {
+ // Check tsconfig time
+ var configStatus = checkConfigFileUpToDateStatus(project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
+ if (configStatus)
+ return configStatus;
+ // Check extended config time
+ var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName); });
+ if (extendedConfigStatus)
+ return extendedConfigStatus;
+ }
+ if (!buildInfoChecked.hasKey(project.options.configFilePath)) {
+ buildInfoChecked.setValue(project.options.configFilePath, true);
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath) {
+ var value = readFileWithCache(buildInfoPath);
+ var buildInfo = value && ts.getBuildInfo(value);
+ if (buildInfo && buildInfo.version !== ts.version) {
+ return {
+ type: UpToDateStatusType.TsVersionOutputOfDate,
+ version: buildInfo.version
+ };
+ }
+ }
+ }
if (usesPrepend && pseudoUpToDate) {
return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
+ type: UpToDateStatusType.OutOfDateWithPrepend,
outOfDateOutputFileName: oldestOutputFileName,
newerProjectName: upstreamChangedProject
};
@@ -92289,6 +94084,17 @@
oldestOutputFileName: oldestOutputFileName
};
}
+ function checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName) {
+ // Check tsconfig time
+ var tsconfigTime = host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
+ if (oldestOutputFileTime < tsconfigTime) {
+ return {
+ type: UpToDateStatusType.OutOfDateWithSelf,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerInputFileName: configFile
+ };
+ }
+ }
function invalidateProject(configFileName, reloadLevel) {
invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel);
}
@@ -92407,7 +94213,9 @@
updateOutputTimestamps(proj);
return;
}
- var buildResult = buildSingleProject(resolved);
+ var buildResult = needsBuild(status, resolved) ?
+ buildSingleProject(resolved) : // Actual build
+ updateBundle(resolved); // Fake that files have been built by manipulating prepend and existing output
if (buildResult & BuildResultFlags.AnyErrors)
return;
var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue;
@@ -92423,18 +94231,27 @@
// If declaration output is changed, build the project
// otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
var status_1 = projectStatus.getValue(project);
- if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
- if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) {
+ if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
+ if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status_1.type === UpToDateStatusType.OutOfDateWithPrepend)) {
projectStatus.setValue(project, {
type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: status_1.oldestOutputFileName,
+ outOfDateOutputFileName: status_1.type === UpToDateStatusType.OutOfDateWithPrepend ? status_1.outOfDateOutputFileName : status_1.oldestOutputFileName,
newerProjectName: resolved
});
}
}
else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) {
+ if (prepend) {
+ projectStatus.setValue(project, {
+ type: UpToDateStatusType.OutOfDateWithPrepend,
+ outOfDateOutputFileName: status_1.oldestOutputFileName,
+ newerProjectName: resolved
+ });
+ }
+ else {
status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
}
+ }
addProjToQueue(project);
}
}
@@ -92490,8 +94307,7 @@
}
if (options.verbose)
reportStatus(ts.Diagnostics.Building_project_0, proj);
- var resultFlags = BuildResultFlags.None;
- resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
+ var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
var configFile = parseConfigFile(proj);
if (!configFile) {
// Failed to read the config file
@@ -92507,8 +94323,7 @@
}
// TODO: handle resolve module name to cache result in project reference redirect
projectCompilerOptions = configFile.options;
- var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences);
- projectCompilerOptions = baseCompilerOptions;
+ var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, getOldProgram(proj, configFile), configFile.errors, configFile.projectReferences);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
@@ -92564,17 +94379,19 @@
var status = {
type: UpToDateStatusType.UpToDate,
newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime,
- oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile)
+ oldestOutputFileName: outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(configFile, !host.useCaseSensitiveFileNames())
};
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
}
}
@@ -92587,15 +94404,71 @@
builderPrograms.setValue(proj, program);
}
}
+ function getOldProgram(proj, parsed) {
+ if (options.force)
+ return undefined;
+ var value = builderPrograms.getValue(proj);
+ if (value)
+ return value;
+ return ts.readBuilderProgram(parsed.options, readFileWithCache);
+ }
+ function updateBundle(proj) {
+ if (options.dry) {
+ reportStatus(ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
+ return BuildResultFlags.Success;
+ }
+ if (options.verbose)
+ reportStatus(ts.Diagnostics.Updating_output_of_project_0, proj);
+ // Update js, and source map
+ var config = ts.Debug.assertDefined(parseConfigFile(proj));
+ projectCompilerOptions = config.options;
+ var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) { return parseConfigFile(resolveProjectName(ref.path)); });
+ if (ts.isString(outputFiles)) {
+ reportStatus(ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
+ return buildSingleProject(proj);
+ }
+ // Actual Emit
+ ts.Debug.assert(!!outputFiles.length);
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ var emittedOutputs = createFileMap(toPath);
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
+ emittedOutputs.setValue(name, true);
+ ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
+ });
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
+ reportAndStoreErrors(proj, emitDiagnostics);
+ projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
+ }
+ // Update timestamps for dts
+ var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
+ oldestOutputFileName: outputFiles[0].name
+ };
+ diagnostics.removeKey(proj);
+ projectStatus.setValue(proj, status);
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged;
+ }
function updateOutputTimestamps(proj) {
if (options.dry) {
- return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
+ return reportStatus(ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
}
var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
- projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
+ oldestOutputFileName: ts.getFirstProjectOutput(proj, !host.useCaseSensitiveFileNames())
+ };
+ projectStatus.setValue(proj.options.configFilePath, status);
}
function updateOutputTimestampsWorker(proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
- var outputs = getAllProjectOutputs(proj);
+ var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
if (!skipOutputs || outputs.length !== skipOutputs.getSize()) {
if (options.verbose) {
reportStatus(verboseMessage, proj.options.configFilePath);
@@ -92629,7 +94502,7 @@
reportParseConfigFileDiagnostic(proj);
continue;
}
- var outputs = getAllProjectOutputs(parsed);
+ var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) {
var output = outputs_3[_b];
if (host.fileExists(output)) {
@@ -92716,7 +94589,9 @@
// Do nothing
continue;
}
- var buildResult = buildSingleProject(next);
+ var buildResult = needsBuild(status, next) ?
+ buildSingleProject(next) : // Actual build
+ updateBundle(next); // Fake that files have been built by manipulating prepend and existing output
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
@@ -92729,6 +94604,15 @@
readFileWithCache = savedReadFileWithCache;
return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
}
+ function needsBuild(status, configFile) {
+ if (status.type !== UpToDateStatusType.OutOfDateWithPrepend || options.force)
+ return true;
+ var config = parseConfigFile(configFile);
+ return !config ||
+ config.fileNames.length === 0 ||
+ !!config.errors.length ||
+ !ts.isIncrementalCompilation(config.options);
+ }
function reportParseConfigFileDiagnostic(proj) {
reportAndStoreErrors(proj, [configFileCache.getValue(proj)]);
}
@@ -92768,33 +94652,6 @@
return ts.combinePaths(project, "tsconfig.json");
}
ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
- function getAllProjectOutputs(project) {
- if (project.options.outFile || project.options.out) {
- 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 getFirstProjectOutput(project) {
- if (project.options.outFile || project.options.out) {
- return ts.first(getOutFileOutputs(project));
- }
- for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
- var inputFile = _a[_i];
- var outputs = getOutputFileNames(inputFile, project);
- if (outputs.length) {
- return ts.first(outputs);
- }
- }
- return ts.Debug.fail("project " + project.options.configFilePath + " expected to have at least one output");
- }
function formatUpToDateStatus(configFileName, status, relName, formatMessage) {
switch (status.type) {
case UpToDateStatusType.OutOfDateWithSelf:
@@ -92809,6 +94666,8 @@
}
// Don't report anything for "up to date because it was already built" -- too verbose
break;
+ case UpToDateStatusType.OutOfDateWithPrepend:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(configFileName), relName(status.newerProjectName));
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:
@@ -92817,6 +94676,8 @@
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.TsVersionOutputOfDate:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(configFileName), status.version, ts.version);
case UpToDateStatusType.ContainerOnly:
// Don't report status on "solution" projects
case UpToDateStatusType.ComputingUpstream:
@@ -92992,6 +94853,11 @@
* typingsInstaller will run the command with `${npmLocation} install ...`.
*/
Arguments.NpmLocation = "--npmLocation";
+ /**
+ * Flag indicating that the typings installer should try to validate the default npm location.
+ * If the default npm is not found when this flag is enabled, fallback to `npm install`
+ */
+ Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
})(Arguments = server.Arguments || (server.Arguments = {}));
function hasArgument(argumentName) {
return ts.sys.args.indexOf(argumentName) >= 0;
@@ -93215,8 +95081,8 @@
if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
continue;
}
- var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- var packageJson = result_7.config;
+ 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.
@@ -93588,7 +95454,7 @@
/* @internal */
var ts;
(function (ts) {
- ts.scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true);
+ ts.scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ true);
var SemanticMeaning;
(function (SemanticMeaning) {
SemanticMeaning[SemanticMeaning["None"] = 0] = "None";
@@ -93623,7 +95489,7 @@
case 242 /* TypeAliasDeclaration */:
case 168 /* TypeLiteral */:
return 2 /* Type */;
- case 304 /* JSDocTypedefTag */:
+ case 309 /* 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 278 /* EnumMember */:
@@ -93648,14 +95514,14 @@
case 255 /* ExportDeclaration */:
return 7 /* All */;
// An external module can be a Value
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 4 /* Namespace */ | 1 /* Value */;
}
return 7 /* All */;
}
ts.getMeaningFromDeclaration = getMeaningFromDeclaration;
function getMeaningFromLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return 1 /* Value */;
}
else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) {
@@ -93861,7 +95727,7 @@
return undefined;
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
case 239 /* FunctionDeclaration */:
@@ -93879,7 +95745,7 @@
ts.getContainerNode = getContainerNode;
function getNodeKind(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */;
case 244 /* ModuleDeclaration */:
return "module" /* moduleElement */;
@@ -93888,8 +95754,8 @@
return "class" /* classElement */;
case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */;
case 242 /* TypeAliasDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return "type" /* typeElement */;
case 243 /* EnumDeclaration */: return "enum" /* enumElement */;
case 237 /* VariableDeclaration */:
@@ -94306,8 +96172,8 @@
isWhiteSpaceOnlyJsxText(child);
if (lookInPreviousChild) {
// actual start of the node is past the position - previous token should be at the end of previous child
- var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
- return candidate_2 && findRightmostToken(candidate_2, sourceFile);
+ var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
+ return candidate_1 && findRightmostToken(candidate_1, sourceFile);
}
else {
// candidate should be in this node
@@ -94315,7 +96181,7 @@
}
}
}
- ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
+ ts.Debug.assert(startNode !== undefined || n.kind === 284 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || 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.
@@ -94402,7 +96268,7 @@
}
ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute;
function isWhiteSpaceOnlyJsxText(node) {
- return ts.isJsxText(node) && node.containsOnlyWhiteSpaces;
+ return ts.isJsxText(node) && node.containsOnlyTriviaWhiteSpaces;
}
function isInTemplateString(sourceFile, position) {
var token = getTokenAtPosition(sourceFile, position);
@@ -95162,6 +97028,17 @@
return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName));
}
ts.getScriptKind = getScriptKind;
+ function getSymbolTarget(symbol) {
+ var next = symbol;
+ while (isTransientSymbol(next) && next.target) {
+ next = next.target;
+ }
+ return next;
+ }
+ ts.getSymbolTarget = getSymbolTarget;
+ function isTransientSymbol(symbol) {
+ return (symbol.flags & 33554432 /* Transient */) !== 0;
+ }
function getUniqueSymbolId(symbol, checker) {
return ts.getSymbolId(ts.skipAlias(symbol, checker));
}
@@ -95220,14 +97097,14 @@
ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext);
if (visited === node) {
// This only happens for leaf nodes - internal nodes always see their children change.
- var clone_8 = ts.getSynthesizedClone(node);
- if (ts.isStringLiteral(clone_8)) {
- clone_8.textSourceNode = node;
+ var clone_1 = ts.getSynthesizedClone(node);
+ if (ts.isStringLiteral(clone_1)) {
+ clone_1.textSourceNode = node;
}
- else if (ts.isNumericLiteral(clone_8)) {
- clone_8.numericLiteralFlags = node.numericLiteralFlags;
+ else if (ts.isNumericLiteral(clone_1)) {
+ clone_1.numericLiteralFlags = node.numericLiteralFlags;
}
- return ts.setTextRange(clone_8, node);
+ return ts.setTextRange(clone_1, node);
}
// PERF: As an optimization, rather than calling getSynthesizedClone, we'll update
// the new node created by visitEachChild with the extra changes getSynthesizedClone
@@ -95313,8 +97190,27 @@
return lastPos;
}
ts.getRenameLocation = getRenameLocation;
- function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
- ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
+ function copyLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyLeadingComments = copyLeadingComments;
+ function copyTrailingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticTrailingComment));
+ }
+ ts.copyTrailingComments = copyTrailingComments;
+ /**
+ * This function copies the trailing comments for the token that comes before `sourceNode`, as leading comments of `targetNode`.
+ * This is useful because sometimes a comment that refers to `sourceNode` will be a leading comment for `sourceNode`, according to the
+ * notion of trivia ownership, and instead will be a trailing comment for the token before `sourceNode`, e.g.:
+ * `function foo(\* not leading comment for a *\ a: string) {}`
+ * The comment refers to `a` but belongs to the `(` token, but we might want to copy it.
+ */
+ function copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyTrailingAsLeadingComments = copyTrailingAsLeadingComments;
+ function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, cb) {
+ return function (pos, end, kind, htnl) {
if (kind === 3 /* MultiLineCommentTrivia */) {
// Remove leading /*
pos += 2;
@@ -95325,10 +97221,9 @@
// Remove leading //
pos += 2;
}
- ts.addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
- });
+ cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
+ };
}
- ts.copyComments = copyComments;
function indexInTextChange(change, name) {
if (ts.startsWith(change, name))
return 0;
@@ -95409,11 +97304,35 @@
return checker.getTypeAtLocation(caseClause.parent.parent.expression);
}
ts.getSwitchedType = getSwitchedType;
+ function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
+ var checker = program.getTypeChecker();
+ var typeIsAccessible = true;
+ var notAccessible = function () { typeIsAccessible = false; };
+ var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
+ trackSymbol: function (symbol, declaration, meaning) {
+ // TODO: GH#18217
+ typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
+ },
+ reportInaccessibleThisError: notAccessible,
+ reportPrivateInBaseOfClassExpression: notAccessible,
+ reportInaccessibleUniqueSymbolError: notAccessible,
+ moduleResolverHost: {
+ readFile: host.readFile,
+ fileExists: host.fileExists,
+ directoryExists: host.directoryExists,
+ getSourceFiles: program.getSourceFiles,
+ getCurrentDirectory: program.getCurrentDirectory,
+ getCommonSourceDirectory: program.getCommonSourceDirectory,
+ }
+ });
+ return typeIsAccessible ? res : undefined;
+ }
+ ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible;
})(ts || (ts = {}));
var ts;
(function (ts) {
function createClassifier() {
- var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false);
+ var scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false);
function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) {
return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text);
}
@@ -95652,7 +97571,7 @@
var lastEnd = 0;
for (var i = 0; i < dense.length; i += 3) {
var start = dense[i];
- var length_5 = dense[i + 1];
+ var length_1 = dense[i + 1];
var type = dense[i + 2];
// Make a whitespace entry between the last item and this one.
if (lastEnd >= 0) {
@@ -95661,8 +97580,8 @@
entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace });
}
}
- entries.push({ length: length_5, classification: convertClassification(type) });
- lastEnd = start + length_5;
+ entries.push({ length: length_1, classification: convertClassification(type) });
+ lastEnd = start + length_1;
}
var whitespaceLength = text.length - lastEnd;
if (whitespaceLength > 0) {
@@ -95967,8 +97886,8 @@
var spanStart = span.start;
var spanLength = span.length;
// Make a scanner we can get trivia from.
- var triviaScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
- var mergeConflictScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
+ var triviaScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
+ var mergeConflictScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
var result = [];
processElement(sourceFile);
return { spans: result, endOfLineState: 0 /* None */ };
@@ -96060,18 +97979,18 @@
pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param"
pos = tag.tagName.end;
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
processJSDocParameterTag(tag);
break;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
processJSDocTemplateTag(tag);
pos = tag.end;
break;
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
@@ -96324,7 +98243,7 @@
return convertPathCompletions(completion.paths);
case 1 /* Properties */: {
var entries = [];
- Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary
+ Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 7 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries };
}
case 2 /* Types */: {
@@ -96375,6 +98294,7 @@
case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */;
case ".ts" /* Ts */: return ".ts" /* tsModifier */;
case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */;
+ case ".tsbuildinfo" /* TsBuildInfo */: return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported.");
case undefined: return "" /* none */;
default:
return ts.Debug.assertNever(extension);
@@ -96605,8 +98525,8 @@
* both foo.ts and foo.tsx become foo
*/
var foundFiles = ts.createMap(); // maps file to its extension
- for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
- var filePath = files_3[_i];
+ for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
+ var filePath = files_1[_i];
filePath = ts.normalizePath(filePath);
if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) {
continue;
@@ -96651,7 +98571,7 @@
continue;
var patterns = paths[path];
if (patterns) {
- var _loop_11 = function (name, kind, extension) {
+ var _loop_1 = function (name, kind, extension) {
// 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, extension));
@@ -96659,7 +98579,7 @@
};
for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) {
var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension;
- _loop_11(name, kind, extension);
+ _loop_1(name, kind, extension);
}
}
}
@@ -96694,7 +98614,7 @@
// (But do if we didn't find anything, e.g. 'package.json' missing.)
var foundGlobal = false;
if (fragmentDirectory === undefined) {
- var _loop_12 = function (moduleName) {
+ var _loop_2 = function (moduleName) {
if (!result.some(function (entry) { return entry.name === moduleName; })) {
foundGlobal = true;
result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined));
@@ -96702,7 +98622,7 @@
};
for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) {
var moduleName = _c[_b];
- _loop_12(moduleName);
+ _loop_2(moduleName);
}
}
if (!foundGlobal) {
@@ -96816,8 +98736,8 @@
// Check for typings specified in compiler options
var seen = ts.createMap();
var typeRoots = tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray;
- for (var _i = 0, typeRoots_2 = typeRoots; _i < typeRoots_2.length; _i++) {
- var root = typeRoots_2[_i];
+ for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
+ var root = typeRoots_1[_i];
getCompletionEntriesFromDirectories(root);
}
// Also get all @types typings installed in visible node_modules directories
@@ -96902,7 +98822,7 @@
var offset = index !== -1 ? index + 1 : 0;
// If the range is an identifier, span is unnecessary.
var length = text.length - offset;
- return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length);
+ return length === 0 || ts.isIdentifierText(text.substr(offset, length), 7 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length);
}
// Returns true if the path is explicitly relative to the script (i.e. relative to . or ..)
function isPathRelativeToScript(path) {
@@ -96987,6 +98907,7 @@
KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords";
KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords";
KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords";
+ KeywordCompletionFilters[KeywordCompletionFilters["Last"] = 6] = "Last";
})(KeywordCompletionFilters || (KeywordCompletionFilters = {}));
var GlobalsSearch;
(function (GlobalsSearch) {
@@ -97032,7 +98953,7 @@
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
}
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;
+ 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, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression;
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.
@@ -97063,7 +98984,7 @@
}
if (keywordFilters !== 0 /* None */) {
var entryNames = ts.arrayToSet(entries, function (e) { return e.name; });
- for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) {
var keywordEntry = _a[_i];
if (!entryNames.has(keywordEntry.name)) {
entries.push(keywordEntry);
@@ -97179,8 +99100,8 @@
// 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_3 = symbols; _i < symbols_3.length; _i++) {
- var symbol = symbols_3[_i];
+ for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
+ var symbol = symbols_1[_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) {
@@ -97399,7 +99320,7 @@
return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
}
function isModuleSymbol(symbol) {
- return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; });
+ return symbol.declarations.some(function (d) { return d.kind === 284 /* SourceFile */; });
}
function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) {
var typeChecker = program.getTypeChecker();
@@ -97450,11 +99371,11 @@
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
return { kind: 1 /* JsDocTagName */ };
}
- if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
currentToken = ts.getTokenAtPosition(sourceFile, position);
if (!currentToken ||
(!ts.isDeclarationName(currentToken) &&
- (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ ||
+ (currentToken.parent.kind !== 310 /* JSDocPropertyTag */ ||
currentToken.parent.name !== currentToken))) {
// Use as type location if inside tag's type expression
insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
@@ -97480,9 +99401,9 @@
// 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_3 = ts.timestamp();
+ var start_1 = ts.timestamp();
contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217
- log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_3));
+ log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1));
}
// Find the node where completion is requested on.
// Also determine whether we are trying to complete with members of that node
@@ -97507,6 +99428,14 @@
case 189 /* PropertyAccessExpression */:
propertyAccessToConvert = parent;
node = propertyAccessToConvert.expression;
+ if (node.end === contextToken.pos &&
+ ts.isCallExpression(node) &&
+ node.getChildCount(sourceFile) &&
+ ts.last(node.getChildren(sourceFile)).kind !== 21 /* CloseParenToken */) {
+ // This is likely dot from incorrectly parsed call expression and user is starting to write spread
+ // eg: Math.min(./**/)
+ return undefined;
+ }
break;
case 148 /* QualifiedName */:
node = parent.left;
@@ -97622,14 +99551,29 @@
var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker);
var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; });
var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker);
- 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 };
+ 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,
+ insideJsDocTagTypeExpression: insideJsDocTagTypeExpression
+ };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 304 /* JSDocTypedefTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 309 /* JSDocTypedefTag */:
return true;
default:
return false;
@@ -97669,7 +99613,9 @@
}
}
// 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 !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
+ if (!isTypeLocation &&
+ symbol.declarations &&
+ symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node));
}
return;
@@ -97802,8 +99748,8 @@
var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 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 !== 279 /* SourceFile */) {
- var thisType = typeChecker.tryGetThisTypeAt(scopeNode);
+ if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 284 /* SourceFile */) {
+ var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false);
if (thisType) {
for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) {
var symbol = _a[_i];
@@ -97835,7 +99781,7 @@
}
function isSnippetScope(scopeNode) {
switch (scopeNode.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 206 /* TemplateExpression */:
case 270 /* JsxExpression */:
case 218 /* Block */:
@@ -97894,6 +99840,8 @@
return parentKind === 242 /* TypeAliasDeclaration */;
case 119 /* AsKeyword */:
return parentKind === 212 /* AsExpression */;
+ case 86 /* ExtendsKeyword */:
+ return parentKind === 150 /* TypeParameter */;
}
}
return false;
@@ -98590,7 +100538,15 @@
}
return res;
});
- function getKeywordCompletions(keywordFilter) {
+ function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) {
+ if (!filterOutTsOnlyKeywords)
+ return getTypescriptKeywordCompletions(keywordFilter);
+ var index = keywordFilter + 6 /* Last */ + 1;
+ return _keywordCompletions[index] ||
+ (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter)
+ .filter(function (entry) { return !isTypeScriptOnlyKeyword(ts.stringToToken(entry.name)); }));
+ }
+ function getTypescriptKeywordCompletions(keywordFilter) {
return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) {
var kind = ts.stringToToken(entry.name);
switch (keywordFilter) {
@@ -98614,6 +100570,39 @@
}
}));
}
+ function isTypeScriptOnlyKeyword(kind) {
+ switch (kind) {
+ case 118 /* AbstractKeyword */:
+ case 120 /* AnyKeyword */:
+ case 146 /* BigIntKeyword */:
+ case 123 /* BooleanKeyword */:
+ case 125 /* DeclareKeyword */:
+ case 84 /* EnumKeyword */:
+ case 145 /* GlobalKeyword */:
+ case 109 /* ImplementsKeyword */:
+ case 127 /* InferKeyword */:
+ case 110 /* InterfaceKeyword */:
+ case 128 /* IsKeyword */:
+ case 129 /* KeyOfKeyword */:
+ case 130 /* ModuleKeyword */:
+ case 131 /* NamespaceKeyword */:
+ case 132 /* NeverKeyword */:
+ case 135 /* NumberKeyword */:
+ case 136 /* ObjectKeyword */:
+ case 113 /* PrivateKeyword */:
+ case 114 /* ProtectedKeyword */:
+ case 115 /* PublicKeyword */:
+ case 133 /* ReadonlyKeyword */:
+ case 138 /* StringKeyword */:
+ case 139 /* SymbolKeyword */:
+ case 140 /* TypeKeyword */:
+ case 142 /* UniqueKeyword */:
+ case 143 /* UnknownKeyword */:
+ return true;
+ default:
+ return false;
+ }
+ }
function isInterfaceOrTypeLiteralCompletionKeyword(kind) {
return kind === 133 /* ReadonlyKeyword */;
}
@@ -98667,7 +100656,7 @@
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 306 /* SyntaxList */:
+ case 311 /* 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);
@@ -98852,7 +100841,7 @@
var child = throwStatement;
while (child.parent) {
var parent = child.parent;
- if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) {
+ if (ts.isFunctionBlock(parent) || parent.kind === 284 /* SourceFile */) {
return parent;
}
// A throw-statement is only owned by a try-statement if the try-statement has
@@ -98910,7 +100899,7 @@
var container = declaration.parent;
switch (container.kind) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 271 /* CaseClause */:
case 272 /* DefaultClause */:
@@ -99408,7 +101397,7 @@
}
else if (!isAvailableThroughGlobal) {
var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
- ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
+ ts.Debug.assert(sourceFileLike.kind === 284 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
addIndirectUsers(sourceFileLike);
}
@@ -99517,7 +101506,7 @@
}
}
/**
- * `import x = require("./x") or `import * as x from "./x"`.
+ * `import x = require("./x")` or `import * as x from "./x"`.
* An `export =` may be imported by this syntax, so it may be a direct import.
* If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here.
*/
@@ -99574,10 +101563,10 @@
function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
var refs = [];
var checker = program.getTypeChecker();
- for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
- var referencingFile = sourceFiles_3[_i];
+ for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
+ var referencingFile = sourceFiles_1[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
- if (searchSourceFile.kind === 279 /* SourceFile */) {
+ if (searchSourceFile.kind === 284 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
var ref = _b[_a];
if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
@@ -99605,8 +101594,8 @@
/** 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_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
- var sourceFile = sourceFiles_4[_i];
+ for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
+ var sourceFile = sourceFiles_2[_i];
if (cancellationToken)
cancellationToken.throwIfCancellationRequested();
forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
@@ -99625,7 +101614,7 @@
}
/** 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 === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
+ return ts.forEach(sourceFileLike.kind === 284 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action));
});
}
@@ -99849,7 +101838,7 @@
return node.getSourceFile();
}
var parent = node.parent;
- if (parent.kind === 279 /* SourceFile */) {
+ if (parent.kind === 284 /* SourceFile */) {
return parent;
}
ts.Debug.assert(parent.kind === 245 /* ModuleBlock */);
@@ -99911,16 +101900,16 @@
}
FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition;
function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* 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 === 276 /* ShorthandPropertyAssignment */) {
- var result_8 = [];
- FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_8.push(nodeEntry(node)); });
- return result_8;
+ var result_1 = [];
+ FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); });
+ return result_1;
}
else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
@@ -99952,27 +101941,27 @@
case 0 /* Symbol */: {
var symbol = def.symbol;
var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
- var name_4 = 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_4, kind: kind_1, displayParts: displayParts_1 };
+ 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 };
}
case 1 /* Label */: {
- 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)] };
+ 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)] };
}
case 2 /* Keyword */: {
- var node_4 = def.node;
- var name_5 = ts.tokenToString(node_4.kind);
- return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] };
+ 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 */ }] };
}
case 3 /* This */: {
- 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 };
+ 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 };
}
case 4 /* String */: {
- 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)] };
+ 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)] };
}
default:
return ts.Debug.assertNever(def);
@@ -100131,8 +102120,8 @@
case 248 /* ImportEqualsDeclaration */:
case 253 /* ImportSpecifier */:
case 241 /* InterfaceDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
case 267 /* JsxAttribute */:
case 244 /* ModuleDeclaration */:
case 247 /* NamespaceExportDeclaration */:
@@ -100157,8 +102146,8 @@
return !!decl.initializer || ts.isCatchClause(decl.parent);
case 155 /* MethodSignature */:
case 153 /* PropertySignature */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
return false;
default:
return ts.Debug.failBadSyntaxKind(decl);
@@ -100250,7 +102239,7 @@
result = references;
continue;
}
- var _loop_13 = function (entry) {
+ var _loop_3 = function (entry) {
if (!entry.definition || entry.definition.type !== 0 /* Symbol */) {
result.push(entry);
return "continue";
@@ -100282,7 +102271,7 @@
};
for (var _b = 0, references_1 = references; _b < references_1.length; _b++) {
var entry = references_1[_b];
- _loop_13(entry);
+ _loop_3(entry);
}
}
return result;
@@ -100318,7 +102307,7 @@
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
switch (decl.kind) {
- case 279 /* SourceFile */:
+ case 284 /* 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 244 /* ModuleDeclaration */:
@@ -100391,11 +102380,16 @@
}
else {
var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] });
+ getReferencesInContainerOrFiles(symbol, state, search);
+ }
+ return result;
+ }
+ function getReferencesInContainerOrFiles(symbol, state, search) {
// Try to get the smallest valid scope that we can limit our search to;
// otherwise we'll need to search globally (i.e. include each file).
var scope = getSymbolScope(symbol);
if (scope) {
- getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope)));
+ getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(state.sourceFiles, scope)));
}
else {
// Global search
@@ -100406,8 +102400,6 @@
}
}
}
- return result;
- }
function getSpecialSearchKind(node) {
switch (node.kind) {
case 124 /* ConstructorKeyword */:
@@ -100459,9 +102451,7 @@
* Unlike `Search`, there is only one `State`.
*/
var State = /** @class */ (function () {
- function State(sourceFiles, sourceFilesSet,
- /** True if we're searching for constructor references. */
- specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
+ function State(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
this.sourceFiles = sourceFiles;
this.sourceFilesSet = sourceFilesSet;
this.specialSearchKind = specialSearchKind;
@@ -100542,8 +102532,8 @@
var sourceId = ts.getNodeId(sourceFile);
var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap());
var anyNewSymbols = false;
- for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) {
- var sym = symbols_4[_i];
+ for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
+ var sym = symbols_2[_i];
anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols;
}
return anyNewSymbols;
@@ -100682,14 +102672,14 @@
return undefined;
}
var scope;
- for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) {
- var declaration = declarations_11[_i];
+ for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
+ var declaration = declarations_1[_i];
var container = ts.getContainerNode(declaration);
if (scope && scope !== container) {
// Different declarations have different containers, bail out
return undefined;
}
- if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
+ if (!container || container.kind === 284 /* 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;
@@ -100734,8 +102724,8 @@
if (!signature.name || !ts.isIdentifier(signature.name))
return;
var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name));
- for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
- var sourceFile = sourceFiles_5[_i];
+ for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
+ var sourceFile = sourceFiles_3[_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)
@@ -100776,8 +102766,8 @@
// We found a match. Make sure it's not part of a larger word (i.e. the char
// before and after it have to be a non-identifier char).
var endPosition = position + symbolNameLength;
- if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 6 /* Latest */)) &&
- (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 6 /* Latest */))) {
+ if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 7 /* Latest */)) &&
+ (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 7 /* Latest */))) {
// Found a real match. Keep searching.
positions.push(position);
}
@@ -100926,7 +102916,9 @@
}
// For `export { foo as bar }`, rename `foo`, but not `bar`.
if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) {
- var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */;
+ var isDefaultExport = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */
+ || exportSpecifier.name.originalKeywordKind === 80 /* DefaultKeyword */;
+ var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */;
var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol);
var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker));
searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
@@ -101013,6 +103005,7 @@
var classExtending = tryGetClassByExtendingIdentifier(referenceLocation);
if (classExtending) {
findSuperConstructorAccesses(classExtending, pusher());
+ findInheritedConstructorReferences(classExtending, state);
}
}
}
@@ -101045,12 +103038,16 @@
* Reference the constructor and all calls to `new this()`.
*/
function findOwnConstructorReferences(classSymbol, sourceFile, addNode) {
- for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) {
+ var constructorSymbol = getClassConstructorSymbol(classSymbol);
+ if (constructorSymbol) {
+ for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile);
ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword);
addNode(ctrKeyword);
}
+ }
+ if (classSymbol.exports) {
classSymbol.exports.forEach(function (member) {
var decl = member.valueDeclaration;
if (decl && decl.kind === 156 /* MethodDeclaration */) {
@@ -101065,13 +103062,17 @@
}
});
}
+ }
+ function getClassConstructorSymbol(classSymbol) {
+ return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */);
+ }
/** Find references to `super` in the constructor of an extending class. */
- function findSuperConstructorAccesses(cls, addNode) {
- var ctr = cls.symbol.members.get("__constructor" /* Constructor */);
- if (!ctr) {
+ function findSuperConstructorAccesses(classDeclaration, addNode) {
+ var constructor = getClassConstructorSymbol(classDeclaration.symbol);
+ if (!constructor) {
return;
}
- for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) {
+ for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
ts.Debug.assert(decl.kind === 157 /* Constructor */);
var body = decl.body;
@@ -101084,6 +103085,16 @@
}
}
}
+ function hasOwnConstructor(classDeclaration) {
+ return !!getClassConstructorSymbol(classDeclaration.symbol);
+ }
+ function findInheritedConstructorReferences(classDeclaration, state) {
+ if (hasOwnConstructor(classDeclaration))
+ return;
+ var classSymbol = classDeclaration.symbol;
+ var search = state.createSearch(/*location*/ undefined, classSymbol, /*comingFrom*/ undefined);
+ getReferencesInContainerOrFiles(classSymbol, state, search);
+ }
function addImplementationReferences(refNode, addReference, state) {
// Check if we found a function/propertyAssignment/method with an implementation or initializer
if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) {
@@ -101248,7 +103259,7 @@
staticFlag &= ts.getModifierFlags(searchSpaceNode);
searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) {
return undefined;
}
@@ -101261,7 +103272,7 @@
default:
return undefined;
}
- var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
+ var references = ts.flatMap(searchSpaceNode.kind === 284 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) {
if (!ts.isThis(node)) {
@@ -101280,8 +103291,8 @@
// 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 279 /* SourceFile */:
- return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
+ case 284 /* SourceFile */:
+ return container.kind === 284 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
}
});
}).map(function (n) { return FindAllReferences.nodeEntry(n); });
@@ -101437,8 +103448,8 @@
// To achieve that we will keep iterating until the result stabilizes.
// Remember the last meaning
lastIterationMeaning = meaning;
- for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) {
- var declaration = declarations_12[_i];
+ for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
+ var declaration = declarations_2[_i];
var declarationMeaning = ts.getMeaningFromDeclaration(declaration);
if (declarationMeaning & meaning) {
meaning |= declarationMeaning;
@@ -101587,8 +103598,8 @@
// 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_5 = elements; _i < elements_5.length; _i++) {
- var element = elements_5[_i];
+ for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
+ var element = elements_1[_i];
foundExactMatch = tryUpdateString(element) || foundExactMatch;
}
return foundExactMatch;
@@ -101610,7 +103621,7 @@
}
function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) {
var allFiles = program.getSourceFiles();
- var _loop_14 = function (sourceFile) {
+ var _loop_4 = function (sourceFile) {
var newFromOld = oldToNew(sourceFile.path);
var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path;
var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath);
@@ -101642,7 +103653,7 @@
};
for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) {
var sourceFile = allFiles_1[_i];
- _loop_14(sourceFile);
+ _loop_4(sourceFile);
}
}
function combineNormal(pathA, pathB) {
@@ -101672,9 +103683,9 @@
return undefined;
// First try resolved module
if (resolved.resolvedModule) {
- var result_9 = tryChange(resolved.resolvedModule.resolvedFileName);
- if (result_9)
- return result_9;
+ var result_2 = tryChange(resolved.resolvedModule.resolvedFileName);
+ if (result_2)
+ return result_2;
}
// Then failed lookups except package.json since we dont want to touch them (only included ts/js files)
var result = ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson);
@@ -101784,10 +103795,10 @@
// bar<Test>(({pr/*goto*/op1})=>{});
if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) &&
(node === (parent.propertyName || parent.name))) {
- var name_6 = ts.getNameFromPropertyName(node);
+ var name_3 = ts.getNameFromPropertyName(node);
var type = typeChecker.getTypeAtLocation(parent.parent);
- return name_6 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) {
- var prop = t.getProperty(name_6);
+ 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);
});
}
@@ -102135,11 +104146,11 @@
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return [declaration];
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return [declaration, declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
@@ -102160,16 +104171,16 @@
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
var name = tag.name;
return name ? withNode(name) : comment;
default:
@@ -102380,7 +104391,7 @@
: undefined;
return { commentOwner: commentOwner, parameters: parameters_1 };
}
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return "quit";
case 244 /* ModuleDeclaration */:
// If in walking up the tree, we hit a a nested namespace declaration,
@@ -102432,7 +104443,7 @@
if (!patternMatcher)
return ts.emptyArray;
var rawItems = [];
- var _loop_15 = function (sourceFile) {
+ var _loop_5 = function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
if (excludeDtsFiles && sourceFile.isDeclarationFile) {
return "continue";
@@ -102442,9 +104453,9 @@
});
};
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
- for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
- var sourceFile = sourceFiles_6[_i];
- _loop_15(sourceFile);
+ for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
+ var sourceFile = sourceFiles_4[_i];
+ _loop_5(sourceFile);
}
rawItems.sort(compareNavigateToItems);
return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem);
@@ -102457,8 +104468,8 @@
if (!match) {
return; // continue to next named declarations
}
- for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) {
- var declaration = declarations_13[_i];
+ for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
+ var declaration = declarations_3[_i];
if (!shouldKeepItem(declaration, checker))
continue;
if (patternMatcher.patternContainsDots) {
@@ -102940,7 +104951,7 @@
}
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
var sourceFile = node;
return ts.isExternalModule(sourceFile)
? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\""
@@ -102992,10 +105003,10 @@
case 243 /* EnumDeclaration */:
case 241 /* InterfaceDeclaration */:
case 244 /* ModuleDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 242 /* TypeAliasDeclaration */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return true;
case 157 /* Constructor */:
case 156 /* MethodDeclaration */:
@@ -103016,7 +105027,7 @@
}
switch (navigationBarNodeKind(item.parent)) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
return true;
@@ -103101,7 +105112,7 @@
return !member.name || member.name.kind === 149 /* ComputedPropertyName */;
}
function getNodeSpan(node) {
- return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
+ return node.kind === 284 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
}
function getModifiers(node) {
if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) {
@@ -103222,8 +105233,8 @@
else {
// Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: false,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include,
suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
});
}
@@ -103237,7 +105248,7 @@
function removeUnusedImports(oldImports, sourceFile, program) {
var typeChecker = program.getTypeChecker();
var jsxNamespace = typeChecker.getJsxNamespace(sourceFile);
- var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */);
+ var jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */);
var usedImports = [];
for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) {
var importDecl = oldImports_1[_i];
@@ -103561,8 +105572,8 @@
var lastSingleLineCommentEnd = -1;
var singleLineCommentCount = 0;
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;
+ 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;
cancellationToken.throwIfCancellationRequested();
switch (kind) {
case 2 /* SingleLineCommentTrivia */:
@@ -103948,7 +105959,7 @@
if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
return true;
}
- if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) {
+ if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 7 /* Latest */)) {
return false;
}
// TODO: find a way to determine this for any unicode characters in a
@@ -103961,7 +105972,7 @@
if (ch >= 97 /* a */ && ch <= 122 /* z */) {
return true;
}
- if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) {
+ if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 7 /* Latest */)) {
return false;
}
// TODO: find a way to determine this for any unicode characters in a
@@ -103972,15 +105983,15 @@
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(str, value) {
var n = str.length - value.length;
- var _loop_16 = function (start) {
+ var _loop_6 = 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_1 = _loop_6(start);
+ if (typeof state_1 === "object")
+ return state_1.value;
}
return -1;
}
@@ -104991,7 +107002,7 @@
return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
}
function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) {
- var _loop_17 = function (n) {
+ var _loop_7 = 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); });
@@ -105001,9 +107012,9 @@
}
};
for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) {
- var state_5 = _loop_17(n);
- if (typeof state_5 === "object")
- return state_5.value;
+ var state_2 = _loop_7(n);
+ if (typeof state_2 === "object")
+ return state_2.value;
}
return undefined;
}
@@ -105078,13 +107089,13 @@
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); })));
+ var params = ts.createNodeArray(thisParameter.concat(checker.getExpandedParameters(candidateSignature).map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); })));
printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer);
});
return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) };
}
function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
- var isVariadic = candidateSignature.hasRestParameter;
+ var isVariadic = checker.hasEffectiveRestParameter(candidateSignature);
var printer = ts.createPrinter({ removeComments: true });
var typeParameterParts = ts.mapToDisplayParts(function (writer) {
if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) {
@@ -105092,7 +107103,7 @@
printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer);
}
});
- var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); });
+ var parameters = checker.getExpandedParameters(candidateSignature).map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); });
return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] };
}
function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) {
@@ -105281,8 +107292,8 @@
var name = importNameForConvertToDefaultImport(importNode);
if (!name)
continue;
- var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
- var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName);
+ var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
+ var resolvedFile = module && program.getSourceFile(module.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));
}
@@ -105297,8 +107308,8 @@
case 196 /* FunctionExpression */:
var decl = ts.getDeclarationOfExpando(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;
}
@@ -105735,7 +107746,7 @@
displayParts.push(ts.spacePart());
addFullSymbolName(symbol);
}
- if (symbolFlags & 1536 /* Module */) {
+ if (symbolFlags & 1536 /* Module */ && !isThisExpression) {
prefixNextMeaning();
var declaration = ts.getDeclarationOfKind(symbol, 244 /* ModuleDeclaration */);
var isNamespace = declaration && declaration.name && declaration.name.kind === 72 /* Identifier */;
@@ -105919,7 +107930,7 @@
// 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 === 279 /* SourceFile */; })) {
+ if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 284 /* SourceFile */; })) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) {
@@ -106044,7 +108055,7 @@
// 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 === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
+ if (parent.kind === 284 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
return false;
}
}
@@ -106158,7 +108169,7 @@
return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
});
options = ts.cloneCompilerOptions(options);
- var _loop_18 = function (opt) {
+ var _loop_8 = function (opt) {
if (!ts.hasProperty(options, opt.name)) {
return "continue";
}
@@ -106177,7 +108188,7 @@
};
for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
var opt = commandLineOptionsStringToEnum_1[_i];
- _loop_18(opt);
+ _loop_8(opt);
}
return options;
}
@@ -106273,8 +108284,8 @@
(function (ts) {
var formatting;
(function (formatting) {
- var standardScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
- var jsxScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */);
+ var standardScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
+ var jsxScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */);
var ScanAction;
(function (ScanAction) {
ScanAction[ScanAction["Scan"] = 0] = "Scan";
@@ -106868,7 +108879,7 @@
case 226 /* ForInStatement */:
// "in" keyword in [P in keyof T]: T[P]
case 150 /* TypeParameter */:
- return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */;
+ return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */ || context.currentTokenSpan.kind === 59 /* EqualsToken */ || context.nextTokenSpan.kind === 59 /* EqualsToken */;
// Technically, "of" is not a binary operator, but format it the same way as "in"
case 227 /* ForOfStatement */:
return context.currentTokenSpan.kind === 147 /* OfKeyword */ || context.nextTokenSpan.kind === 147 /* OfKeyword */;
@@ -107369,7 +109380,7 @@
case 244 /* ModuleDeclaration */:
var body = parent.body;
return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 245 /* ModuleBlock */:
return ts.rangeContainsRange(parent.statements, node);
@@ -108488,7 +110499,7 @@
// - 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 === 279 /* SourceFile */ || !parentAndChildShareLine);
+ (parent.kind === 284 /* SourceFile */ || !parentAndChildShareLine);
if (!useActualIndentation) {
return -1 /* Unknown */;
}
@@ -108576,7 +110587,7 @@
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return getList(node.typeParameters);
case 192 /* NewExpression */:
case 191 /* CallExpression */:
@@ -108825,11 +110836,23 @@
ts.Debug.assert(typeof end === "number");
n.__end = end;
}
- var Position;
- (function (Position) {
- Position[Position["FullStart"] = 0] = "FullStart";
- Position[Position["Start"] = 1] = "Start";
- })(Position = textChanges_3.Position || (textChanges_3.Position = {}));
+ var LeadingTriviaOption;
+ (function (LeadingTriviaOption) {
+ /** Exclude all leading trivia (use getStart()) */
+ LeadingTriviaOption[LeadingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include leading trivia and,
+ * if there are no line breaks between the node and the previous token,
+ * include all trivia between the node and the previous token
+ */
+ LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll";
+ })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {}));
+ var TrailingTriviaOption;
+ (function (TrailingTriviaOption) {
+ /** Exclude all trailing trivia (use getEnd()) */
+ TrailingTriviaOption[TrailingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include trailing trivia */
+ TrailingTriviaOption[TrailingTriviaOption["Include"] = 1] = "Include";
+ })(TrailingTriviaOption = textChanges_3.TrailingTriviaOption || (textChanges_3.TrailingTriviaOption = {}));
function skipWhitespacesAndLineBreaks(text, start) {
return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
@@ -108845,9 +110868,9 @@
}
return false;
}
- textChanges_3.useNonAdjustedPositions = {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: true,
+ var useNonAdjustedPositions = {
+ leadingTriviaOption: LeadingTriviaOption.Exclude,
+ trailingTriviaOption: TrailingTriviaOption.Exclude,
};
var ChangeKind;
(function (ChangeKind) {
@@ -108857,10 +110880,11 @@
ChangeKind[ChangeKind["Text"] = 3] = "Text";
})(ChangeKind || (ChangeKind = {}));
function getAdjustedRange(sourceFile, startNode, endNode, options) {
- return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) };
+ return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) };
}
- function getAdjustedStartPosition(sourceFile, node, options, position) {
- if (options.useNonAdjustedStartPosition) {
+ function getAdjustedStartPosition(sourceFile, node, options) {
+ var leadingTriviaOption = options.leadingTriviaOption;
+ if (leadingTriviaOption === LeadingTriviaOption.Exclude) {
return node.getStart(sourceFile);
}
var fullStart = node.getFullStart();
@@ -108878,7 +110902,7 @@
// fullstart
// when b is replaced - we usually want to keep the leading trvia
// when b is deleted - we delete it
- return position === Position.Start ? start : fullStart;
+ return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start;
}
// get start position of the line following the line that contains fullstart position
// (but only if the fullstart isn't the very beginning of the file)
@@ -108890,11 +110914,12 @@
}
function getAdjustedEndPosition(sourceFile, node, options) {
var end = node.end;
- if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
+ var trailingTriviaOption = options.trailingTriviaOption;
+ if (trailingTriviaOption === TrailingTriviaOption.Exclude || (ts.isExpression(node) && trailingTriviaOption !== TrailingTriviaOption.Include)) {
return end;
}
var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
- return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
+ return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)))
? newEnd
: end;
}
@@ -108939,15 +110964,15 @@
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 = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
- var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
+ var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
@@ -108955,11 +110980,11 @@
this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
};
ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
};
ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options);
};
ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
@@ -108967,14 +110992,14 @@
this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
};
ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
};
ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
- this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text);
+ this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text);
};
ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
@@ -109002,7 +111027,7 @@
};
ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) {
if (blankLineBetween === void 0) { blankLineBetween = false; }
- this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
+ this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
};
ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) {
var pos = before.getStart(sourceFile);
@@ -109109,7 +111134,7 @@
this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true));
};
ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) {
- var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start);
+ var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {});
this.insertNodeAt(sourceFile, pos, newNode, {
prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
suffix: this.newLineCharacter
@@ -109349,7 +111374,7 @@
ChangeTracker.prototype.finishDeleteDeclarations = function () {
var _this = this;
var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
- var _loop_19 = function (sourceFile, node) {
+ var _loop_9 = 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));
@@ -109362,7 +111387,7 @@
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_19(sourceFile, node);
+ _loop_9(sourceFile, node);
}
deletedNodesInLists.forEach(function (node) {
var sourceFile = node.getSourceFile();
@@ -109399,7 +111424,7 @@
textChanges_3.ChangeTracker = ChangeTracker;
// find first non-whitespace position in the leading trivia of the node
function startPositionToDeleteNodeInList(sourceFile, node) {
- return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
function getClassOrObjectBraceEnds(cls, sourceFile) {
return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end];
@@ -109419,14 +111444,14 @@
// 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_20 = function (i) {
+ var _loop_10 = 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_20(i);
+ _loop_10(i);
}
var textChanges = normalized.map(function (c) {
return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
@@ -109443,7 +111468,7 @@
function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) {
// TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this
var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter);
- var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind);
+ var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 7 /* ESNext */, /*setParentNodes*/ true, scriptKind);
var changes = ts.formatting.formatDocument(sourceFile, formatContext);
return applyChanges(nonFormattedText, changes) + newLineCharacter;
}
@@ -109736,7 +111761,7 @@
case 249 /* ImportDeclaration */:
deleteNode(changes, sourceFile, node,
// For first import, leave header comment in place
- node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined);
+ node === sourceFile.imports[0].parent ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined);
break;
case 186 /* BindingElement */:
var pattern = node.parent;
@@ -109774,7 +111799,7 @@
deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
}
else {
- deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined);
+ deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { trailingTriviaOption: TrailingTriviaOption.Exclude } : undefined);
}
}
}
@@ -109845,8 +111870,8 @@
/** 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);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, node, options);
var endPosition = getAdjustedEndPosition(sourceFile, node, options);
changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
}
@@ -110033,6 +112058,40 @@
(function (ts) {
var codefix;
(function (codefix) {
+ var fixId = "addNameToNamelessParameter";
+ var errorCodes = [ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_parameter_name, fixId, ts.Diagnostics.Add_names_to_all_parameters_without_names)];
+ },
+ fixIds: [fixId],
+ 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);
+ if (!ts.isIdentifier(token)) {
+ return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.formatSyntaxKind(token.kind));
+ }
+ var param = token.parent;
+ if (!ts.isParameter(param)) {
+ return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.formatSyntaxKind(token.kind));
+ }
+ var i = param.parent.parameters.indexOf(param);
+ ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one.");
+ ts.Debug.assert(i > -1, "Parameter not found in parent parameter list.");
+ var replacement = ts.createParameter(
+ /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer);
+ changeTracker.replaceNode(sourceFile, token, replacement);
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
var fixId = "annotateWithTypeFromJSDoc";
var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code];
codefix.registerCodeFix({
@@ -110105,18 +112164,18 @@
}
function transformJSDocType(node) {
switch (node.kind) {
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 164 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -110140,7 +112199,7 @@
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
+ var isRest = node.type.kind === 295 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
var name = node.name || (isRest ? "rest" : "arg" + index);
var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken;
return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
@@ -110296,7 +112355,7 @@
}
if (ts.isPropertyAccessExpression(parent)) {
var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken);
- var typeNode = getTypeNodeIfAccessible(type, parent, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host);
if (typeNode) {
// Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags
var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ "");
@@ -110400,7 +112459,7 @@
}
}
function annotate(changes, sourceFile, declaration, type, program, host) {
- var typeNode = getTypeNodeIfAccessible(type, declaration, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host);
if (typeNode) {
if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) {
var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration;
@@ -110426,7 +112485,7 @@
// only infer parameters that have (1) no type and (2) an accessible inferred type
if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name))
return;
- var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host);
+ var typeNode = inference.type && ts.getTypeNodeIfAccessible(inference.type, param, program, host);
var name = ts.getSynthesizedClone(param.name);
ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), "");
@@ -110443,47 +112502,33 @@
return !!merged;
}); });
var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray((oldTags || ts.emptyArray).concat(unmergedNewTags)));
- changes.insertJsdocCommentBefore(sourceFile, parent, tag);
+ var jsDocNode = parent.kind === 197 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent;
+ jsDocNode.jsDoc = parent.jsDoc;
+ jsDocNode.jsDocCache = parent.jsDocCache;
+ changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag);
+ }
+ function getJsDocNodeForArrowFunction(signature) {
+ if (signature.parent.kind === 154 /* PropertyDeclaration */) {
+ return signature.parent;
+ }
+ return signature.parent.parent;
}
function tryMergeJsdocTags(oldTag, newTag) {
if (oldTag.kind !== newTag.kind) {
return undefined;
}
switch (oldTag.kind) {
- case 299 /* JSDocParameterTag */: {
+ case 304 /* JSDocParameterTag */: {
var oldParam = oldTag;
var newParam = newTag;
return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText
? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment)
: undefined;
}
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment);
}
}
- function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
- var checker = program.getTypeChecker();
- var typeIsAccessible = true;
- var notAccessible = function () { typeIsAccessible = false; };
- var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
- trackSymbol: function (symbol, declaration, meaning) {
- // TODO: GH#18217
- typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
- },
- reportInaccessibleThisError: notAccessible,
- reportPrivateInBaseOfClassExpression: notAccessible,
- reportInaccessibleUniqueSymbolError: notAccessible,
- moduleResolverHost: {
- readFile: host.readFile,
- fileExists: host.fileExists,
- directoryExists: host.directoryExists,
- getSourceFiles: program.getSourceFiles,
- getCurrentDirectory: program.getCurrentDirectory,
- getCommonSourceDirectory: program.getCommonSourceDirectory,
- }
- });
- return typeIsAccessible ? res : undefined;
- }
function getReferences(token, program, cancellationToken) {
// Position shouldn't matter since token is not a SourceFile.
return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) {
@@ -110782,8 +112827,8 @@
}
function removeLowPriorityInferences(inferences, priorities) {
var toRemove = [];
- for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
- var i = inferences_2[_i];
+ for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
+ var i = inferences_1[_i];
for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) {
var _b = priorities_1[_a], high = _b.high, low = _b.low;
if (high(i)) {
@@ -110875,8 +112920,8 @@
types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); }));
if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) {
var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217
- var types_19 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); });
- types_19.push(checker.createPromiseType(types_19.length ? checker.getUnionType(types_19, 2 /* Subtype */) : checker.getAnyType()));
+ var types_1 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); });
+ types_1.push(checker.createPromiseType(types_1.length ? checker.getUnionType(types_1, 2 /* Subtype */) : checker.getAnyType()));
}
else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) {
types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)));
@@ -110885,7 +112930,7 @@
types.push(checker.createArrayType(recur(usageContext.numberIndexContext)));
}
else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) {
- var members_6 = ts.createUnderscoreEscapedMap();
+ var members_1 = ts.createUnderscoreEscapedMap();
var callSignatures = [];
var constructSignatures = [];
var stringIndexInfo = void 0;
@@ -110893,7 +112938,7 @@
usageContext.properties.forEach(function (context, name) {
var symbol = checker.createSymbol(4 /* Property */, name);
symbol.type = recur(context);
- members_6.set(name, symbol);
+ members_1.set(name, symbol);
});
}
if (usageContext.callContexts) {
@@ -110911,7 +112956,7 @@
if (usageContext.stringIndexContext) {
stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false);
}
- types.push(checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217
+ types.push(checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217
}
return types;
function recur(innerContext) {
@@ -110996,7 +113041,7 @@
precedingNode = ctorDeclaration.parent.parent;
newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
if (ctorDeclaration.parent.declarations.length === 1) {
- ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
+ ts.copyLeadingComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
changes.delete(sourceFile, precedingNode);
}
else {
@@ -111007,7 +113052,7 @@
if (!newClassDeclaration) {
return undefined;
}
- ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile);
+ ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile);
// Because the preceding node could be touched, we need to insert nodes before delete nodes.
changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
function createClassElementsFromSymbol(symbol) {
@@ -111060,7 +113105,7 @@
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
case 197 /* ArrowFunction */: {
@@ -111078,7 +113123,7 @@
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
default: {
@@ -111088,7 +113133,7 @@
}
var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
/*type*/ undefined, assignmentBinaryExpression.right);
- ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
return prop;
}
}
@@ -111180,7 +113225,7 @@
var newNodes = transformExpression(node, transformer, node);
changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes);
}
- var _loop_21 = function (statement) {
+ var _loop_11 = function (statement) {
ts.forEachChild(statement, function visit(node) {
if (ts.isCallExpression(node)) {
startTransformation(node, statement);
@@ -111192,7 +113237,7 @@
};
for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) {
var statement = returnStatements_1[_i];
- _loop_21(statement);
+ _loop_11(statement);
}
}
function getReturnStatementsWithPromiseHandlers(body) {
@@ -111517,8 +113562,8 @@
if (innerCbBody.length > 0) {
return innerCbBody;
}
- var type_6 = transformer.checker.getTypeAtLocation(func);
- var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType();
+ var type_1 = transformer.checker.getTypeAtLocation(func);
+ var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType();
var rightHandSide = ts.getSynthesizedDeepClone(funcBody);
var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide;
if (!shouldReturn) {
@@ -112844,7 +114889,7 @@
});
typeDeclToMembers.forEach(function (infos, classDeclaration) {
var supers = getAllSupers(classDeclaration, checker);
- var _loop_22 = function (info) {
+ var _loop_12 = function (info) {
// If some superclass added this property, don't add it again.
if (supers.some(function (superClassOrInterface) {
var superInfos = typeDeclToMembers.get(superClassOrInterface);
@@ -112871,7 +114916,7 @@
};
for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
var info = infos_1[_i];
- _loop_22(info);
+ _loop_12(info);
}
});
}));
@@ -113049,6 +115094,40 @@
(function (ts) {
var codefix;
(function (codefix) {
+ var fixId = "addMissingNewOperator";
+ var errorCodes = [ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile, span = context.span;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingNewOperator(t, sourceFile, span); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_new_operator_to_call, fixId, ts.Diagnostics.Add_missing_new_operator_to_all_calls)];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ return addMissingNewOperator(changes, context.sourceFile, diag);
+ }); },
+ });
+ function addMissingNewOperator(changes, sourceFile, span) {
+ var call = ts.cast(findAncestorMatchingSpan(sourceFile, span), ts.isCallExpression);
+ var newExpression = ts.createNew(call.expression, call.typeArguments, call.arguments);
+ changes.replaceNode(sourceFile, call, newExpression);
+ }
+ function findAncestorMatchingSpan(sourceFile, span) {
+ var token = ts.getTokenAtPosition(sourceFile, span.start);
+ var end = ts.textSpanEnd(span);
+ while (token.end < end) {
+ token = token.parent;
+ }
+ return token;
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
var fixName = "fixCannotFindModule";
var fixIdInstallTypesPackage = "installTypesPackage";
var fixIdGenerateTypes = "generateTypes";
@@ -113334,6 +115413,32 @@
(function (ts) {
var codefix;
(function (codefix) {
+ var fixId = "enableExperimentalDecorators";
+ var errorCodes = [
+ 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.code
+ ];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var configFile = context.program.getCompilerOptions().configFile;
+ if (configFile === undefined) {
+ return undefined;
+ }
+ var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) { return makeChange(changeTracker, configFile); });
+ return [codefix.createCodeFixActionNoFixId(fixId, changes, ts.Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)];
+ },
+ fixIds: [fixId],
+ });
+ function makeChange(changeTracker, configFile) {
+ codefix.setJsonCompilerOptionValue(changeTracker, configFile, "experimentalDecorators", ts.createTrue());
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
var fixId = "extendsInterfaceBecomesImplements";
var errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code];
codefix.registerCodeFix({
@@ -113777,7 +115882,7 @@
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 === 286 /* JSDocNullableType */) {
+ if (typeNode.kind === 291 /* 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, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -113797,7 +115902,7 @@
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 291 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -114046,8 +116151,8 @@
outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences));
break;
}
- for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
- var signature = signatures_7[_i];
+ for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
+ var signature = signatures_1[_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));
}
@@ -114094,7 +116199,7 @@
ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined;
});
var contextualType = checker.getContextualType(call);
- var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker) || ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ var returnType = (inJs || !contextualType) ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker);
return ts.createMethod(
/*decorators*/ undefined,
/*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined,
@@ -114130,8 +116235,8 @@
var maxArgsSignature = signatures[0];
var minArgumentCount = signatures[0].minArgumentCount;
var someSigHasRestParameter = false;
- for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
- var sig = signatures_8[_i];
+ for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
+ var sig = signatures_2[_i];
minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount);
if (sig.hasRestParameter) {
someSigHasRestParameter = true;
@@ -114290,8 +116395,8 @@
ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport));
}
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"), {}); });
+ var sourceFile_1 = context.sourceFile;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_1, expr, ts.createPropertyAccess(expr, "default"), {}); });
fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member));
}
return fixes;
@@ -114429,6 +116534,7 @@
return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings));
}
ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText;
+ /* @internal */
var OutputKind;
(function (OutputKind) {
OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals";
@@ -114563,16 +116669,16 @@
}
}
function toPropertyName(name) {
- return ts.isIdentifierText(name, 6 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name);
+ return ts.isIdentifierText(name, 7 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name);
}
// Parses assignments to "this.x" in the constructor into class property declarations
function getConstructorFunctionInstanceProperties(fnAst, members) {
forEachOwnNodeOfFunction(fnAst, function (node) {
if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) &&
ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) {
- var name_7 = node.left.name.text;
- if (!ts.isJsPrivate(name_7)) {
- ts.getOrUpdate(members, name_7, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_7, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); });
+ var name_4 = node.left.name.text;
+ if (!ts.isJsPrivate(name_4)) {
+ ts.getOrUpdate(members, name_4, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_4, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); });
}
}
});
@@ -114607,7 +116713,7 @@
}
function parseExpression(expr) {
var text = "const _ = " + expr;
- var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true);
+ var srcFile = ts.createSourceFile("test.ts", text, 7 /* Latest */, /*setParentNodes*/ true);
return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer;
}
function inferParameterType(_fn, _param) {
@@ -114624,7 +116730,7 @@
}
function isValidIdentifier(name) {
var keyword = ts.stringToToken(name);
- return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */);
+ return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 7 /* ESNext */);
}
function addComment(node, comment) {
if (comment !== undefined)
@@ -115079,7 +117185,7 @@
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 preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 7 /* 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);
@@ -115087,7 +117193,7 @@
});
var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName;
var neededNamedImports = [];
- var _loop_23 = function (element) {
+ var _loop_13 = 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);
@@ -115106,7 +117212,7 @@
};
for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) {
var element = _a[_i];
- _loop_23(element);
+ _loop_13(element);
}
changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName)));
if (neededNamedImports.length) {
@@ -115596,7 +117702,7 @@
// * Module/namespace or source file
if (isScope(current)) {
scopes.push(current);
- if (current.kind === 279 /* SourceFile */) {
+ if (current.kind === 284 /* SourceFile */) {
return scopes;
}
}
@@ -116161,8 +118267,8 @@
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_7 = members; _i < members_7.length; _i++) {
- var member = members_7[_i];
+ for (var _i = 0, members_2 = members; _i < members_2.length; _i++) {
+ var member = members_2[_i];
if (member.pos > maxPos) {
return prevMember || members[0];
}
@@ -116336,7 +118442,7 @@
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_24 = function (i) {
+ var _loop_14 = 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
@@ -116376,7 +118482,7 @@
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_24(i);
+ _loop_14(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
function isInGenericContext(node) {
@@ -116610,7 +118716,7 @@
function isBlockLike(node) {
switch (node.kind) {
case 218 /* Block */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 245 /* ModuleBlock */:
case 271 /* CaseClause */:
return true;
@@ -116927,10 +119033,10 @@
}
function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
var checker = program.getTypeChecker();
- var _loop_25 = function (sourceFile) {
+ var _loop_15 = function (sourceFile) {
if (sourceFile === oldFile)
return "continue";
- var _loop_26 = function (statement) {
+ var _loop_16 = function (statement) {
forEachImportInStatement(statement, function (importNode) {
if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol)
return;
@@ -116952,12 +119058,12 @@
};
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
var statement = _a[_i];
- _loop_26(statement);
+ _loop_16(statement);
}
};
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
- _loop_25(sourceFile);
+ _loop_15(sourceFile);
}
}
function getNamespaceLikeImport(node) {
@@ -116974,7 +119080,7 @@
}
}
function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) {
- var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */);
+ var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 7 /* ESNext */);
var needUniqueName = false;
var toChange = [];
ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) {
@@ -117072,9 +119178,9 @@
if (isTopLevelDeclarationStatement(statement) &&
!isExported(sourceFile, statement, useEs6Exports) &&
forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) {
- var exports_2 = addExport(statement, useEs6Exports);
- if (exports_2)
- return exports_2;
+ var exports = addExport(statement, useEs6Exports);
+ if (exports)
+ return exports;
}
return statement;
});
@@ -117200,7 +119306,7 @@
var movedSymbols = new SymbolSet();
var oldImportsNeededByNewFile = new SymbolSet();
var newFileImportsFromOldFile = new SymbolSet();
- var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 4 /* ContainsJsx */); });
+ var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 2 /* ContainsJsx */); });
var jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx);
if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code)
oldImportsNeededByNewFile.add(jsxNamespaceSymbol);
@@ -117234,7 +119340,7 @@
if (ts.contains(toMove, statement))
continue;
// jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile.
- if (jsxNamespaceSymbol && !!(statement.transformFlags & 4 /* ContainsJsx */)) {
+ if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) {
unusedImportsFromOldFile.delete(jsxNamespaceSymbol);
}
forEachReference(statement, checker, function (symbol) {
@@ -117549,13 +119655,13 @@
var returnStatement_1 = ts.createReturn(expression);
body = ts.createBlock([returnStatement_1], /* multiLine */ true);
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
+ ts.copyLeadingComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
}
else if (actionName === removeBracesActionName && returnStatement) {
var actualExpression = expression || ts.createVoidZero();
body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression;
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
+ ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
}
else {
ts.Debug.fail("invalid action");
@@ -117594,6 +119700,459 @@
})(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var convertParamsToDestructuredObject;
+ (function (convertParamsToDestructuredObject) {
+ var refactorName = "Convert parameters to destructured object";
+ var minimumParameterLength = 2;
+ refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
+ function getAvailableActions(context) {
+ var file = context.file, startPosition = context.startPosition;
+ var isJSFile = ts.isSourceFileJS(file);
+ if (isJSFile)
+ return ts.emptyArray; // TODO: GH#30113
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
+ if (!functionDeclaration)
+ return ts.emptyArray;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_parameters_to_destructured_object);
+ return [{
+ name: refactorName,
+ description: description,
+ actions: [{
+ name: refactorName,
+ description: description
+ }]
+ }];
+ }
+ function getEditsForAction(context, actionName) {
+ ts.Debug.assert(actionName === refactorName);
+ var file = context.file, startPosition = context.startPosition, program = context.program, cancellationToken = context.cancellationToken, host = context.host;
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker());
+ if (!functionDeclaration || !cancellationToken)
+ return undefined;
+ var groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken);
+ if (groupedReferences.valid) {
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(file, program, host, t, functionDeclaration, groupedReferences); });
+ return { renameFilename: undefined, renameLocation: undefined, edits: edits };
+ }
+ return { edits: [] }; // TODO: GH#30113
+ }
+ function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) {
+ var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); });
+ changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ",
+ // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
+ indentation: 0,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include
+ });
+ var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); });
+ for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) {
+ var call = functionCalls_1[_i];
+ if (call.arguments && call.arguments.length) {
+ var newArgument = ts.getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true);
+ changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include });
+ }
+ }
+ }
+ function getGroupedReferences(functionDeclaration, program, cancellationToken) {
+ var functionNames = getFunctionNames(functionDeclaration);
+ var classNames = ts.isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
+ var names = ts.deduplicate(functionNames.concat(classNames), ts.equateValues);
+ var checker = program.getTypeChecker();
+ var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); });
+ var groupedReferences = groupReferences(references);
+ if (!ts.every(groupedReferences.declarations, /*callback*/ function (/*callback*/ decl) { return ts.contains(names, decl); })) {
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ function groupReferences(referenceEntries) {
+ var classReferences = { accessExpressions: [], typeUsages: [] };
+ var groupedReferences = { functionCalls: [], declarations: [], classReferences: classReferences, valid: true };
+ var functionSymbols = ts.map(functionNames, checker.getSymbolAtLocation);
+ var classSymbols = ts.map(classNames, checker.getSymbolAtLocation);
+ var isConstructor = ts.isConstructorDeclaration(functionDeclaration);
+ for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
+ var entry = referenceEntries_1[_i];
+ if (entry.kind !== 1 /* Node */) {
+ groupedReferences.valid = false;
+ continue;
+ }
+ /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function.
+ Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test:
+ class A { foo(a: number, b: number) { return a + b; } }
+ class B { foo(c: number, d: number) { return c + d; } }
+ declare const ab: A | B;
+ ab.foo(1, 2);
+ Find all references will return `ab.foo(1, 2)` as a reference to A's `foo` but we could be calling B's `foo`.
+ When looking for constructor calls, however, the symbol on the constructor call reference is going to be the corresponding class symbol.
+ So we need to add a special case for this because when calling a constructor of a class through one of its subclasses,
+ the symbols are going to be different.
+ */
+ if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer) || ts.isNewExpressionTarget(entry.node)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var call = entryToFunctionCall(entry);
+ if (call) {
+ groupedReferences.functionCalls.push(call);
+ continue;
+ }
+ }
+ // if the refactored function is a constructor, we must also check if the references to its class are valid
+ if (isConstructor && ts.contains(classSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var accessExpression = entryToAccessExpression(entry);
+ if (accessExpression) {
+ classReferences.accessExpressions.push(accessExpression);
+ continue;
+ }
+ // Only class declarations are allowed to be used as a type (in a heritage clause),
+ // otherwise `findAllReferences` might not be able to track constructor calls.
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ var type = entryToType(entry);
+ if (type) {
+ classReferences.typeUsages.push(type);
+ continue;
+ }
+ }
+ }
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ }
+ }
+ function symbolComparer(a, b) {
+ return ts.getSymbolTarget(a) === ts.getSymbolTarget(b);
+ }
+ function entryToDeclaration(entry) {
+ if (ts.isDeclaration(entry.node.parent)) {
+ return entry.node;
+ }
+ return undefined;
+ }
+ function entryToFunctionCall(entry) {
+ if (entry.node.parent) {
+ var functionReference = entry.node;
+ var parent = functionReference.parent;
+ switch (parent.kind) {
+ // Function call (foo(...) or super(...))
+ case 191 /* CallExpression */:
+ var callExpression = ts.tryCast(parent, ts.isCallExpression);
+ if (callExpression && callExpression.expression === functionReference) {
+ return callExpression;
+ }
+ break;
+ // Constructor call (new Foo(...))
+ case 192 /* NewExpression */:
+ var newExpression = ts.tryCast(parent, ts.isNewExpression);
+ if (newExpression && newExpression.expression === functionReference) {
+ return newExpression;
+ }
+ break;
+ // Method call (x.foo(...))
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) {
+ var callExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_1 && callExpression_1.expression === propertyAccessExpression) {
+ return callExpression_1;
+ }
+ }
+ break;
+ // Method call (x["foo"](...))
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) {
+ var callExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_2 && callExpression_2.expression === elementAccessExpression) {
+ return callExpression_2;
+ }
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToAccessExpression(entry) {
+ if (entry.node.parent) {
+ var reference = entry.node;
+ var parent = reference.parent;
+ switch (parent.kind) {
+ // `C.foo`
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.expression === reference) {
+ return propertyAccessExpression;
+ }
+ break;
+ // `C["foo"]`
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.expression === reference) {
+ return elementAccessExpression;
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToType(entry) {
+ var reference = entry.node;
+ if (ts.getMeaningFromLocation(reference) === 2 /* Type */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) {
+ return reference;
+ }
+ return undefined;
+ }
+ function getFunctionDeclarationAtPosition(file, startPosition, checker) {
+ var node = ts.getTouchingToken(file, startPosition);
+ var functionDeclaration = ts.getContainingFunction(node);
+ // don't offer refactor on top-level JSDoc
+ if (isTopLevelJSDoc(node))
+ return undefined;
+ if (functionDeclaration
+ && isValidFunctionDeclaration(functionDeclaration, checker)
+ && ts.rangeContainsRange(functionDeclaration, node)
+ && !(functionDeclaration.body && ts.rangeContainsRange(functionDeclaration.body, node)))
+ return functionDeclaration;
+ return undefined;
+ }
+ function isTopLevelJSDoc(node) {
+ var containingJSDoc = ts.findAncestor(node, ts.isJSDocNode);
+ if (containingJSDoc) {
+ var containingNonJSDoc = ts.findAncestor(containingJSDoc, function (n) { return !ts.isJSDocNode(n); });
+ return !!containingNonJSDoc && ts.isFunctionLikeDeclaration(containingNonJSDoc);
+ }
+ return false;
+ }
+ function isValidFunctionDeclaration(functionDeclaration, checker) {
+ if (!isValidParameterNodeArray(functionDeclaration.parameters, checker))
+ return false;
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return !!functionDeclaration.name
+ && !!functionDeclaration.body
+ && !checker.isImplementationOfOverload(functionDeclaration);
+ case 157 /* Constructor */:
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ return !!functionDeclaration.body
+ && !!functionDeclaration.parent.name
+ && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ else {
+ return isValidVariableDeclaration(functionDeclaration.parent.parent)
+ && !!functionDeclaration.body
+ && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ case 196 /* FunctionExpression */:
+ case 197 /* ArrowFunction */:
+ return isValidVariableDeclaration(functionDeclaration.parent);
+ }
+ return false;
+ }
+ function isValidParameterNodeArray(parameters, checker) {
+ return getRefactorableParametersLength(parameters) >= minimumParameterLength
+ && ts.every(parameters, /*callback*/ function (/*callback*/ paramDecl) { return isValidParameterDeclaration(paramDecl, checker); });
+ }
+ function isValidParameterDeclaration(parameterDeclaration, checker) {
+ if (ts.isRestParameter(parameterDeclaration)) {
+ var type = checker.getTypeAtLocation(parameterDeclaration);
+ if (!checker.isArrayType(type) && !checker.isTupleType(type))
+ return false;
+ }
+ return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name);
+ }
+ function isValidVariableDeclaration(node) {
+ return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113
+ }
+ function hasThisParameter(parameters) {
+ return parameters.length > 0 && ts.isThis(parameters[0].name);
+ }
+ function getRefactorableParametersLength(parameters) {
+ if (hasThisParameter(parameters)) {
+ return parameters.length - 1;
+ }
+ return parameters.length;
+ }
+ function getRefactorableParameters(parameters) {
+ if (hasThisParameter(parameters)) {
+ parameters = ts.createNodeArray(parameters.slice(1), parameters.hasTrailingComma);
+ }
+ return parameters;
+ }
+ function createPropertyOrShorthandAssignment(name, initializer) {
+ if (ts.isIdentifier(initializer) && ts.getTextOfIdentifierOrLiteral(initializer) === name) {
+ return ts.createShorthandPropertyAssignment(name);
+ }
+ return ts.createPropertyAssignment(name, initializer);
+ }
+ function createNewArgument(functionDeclaration, functionArguments) {
+ var parameters = getRefactorableParameters(functionDeclaration.parameters);
+ var hasRestParameter = ts.isRestParameter(ts.last(parameters));
+ var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments;
+ var properties = ts.map(nonRestArguments, function (arg, i) {
+ var parameterName = getParameterName(parameters[i]);
+ var property = createPropertyOrShorthandAssignment(parameterName, arg);
+ ts.suppressLeadingAndTrailingTrivia(property.name);
+ if (ts.isPropertyAssignment(property))
+ ts.suppressLeadingAndTrailingTrivia(property.initializer);
+ copyComments(arg, property);
+ return property;
+ });
+ if (hasRestParameter && functionArguments.length >= parameters.length) {
+ var restArguments = functionArguments.slice(parameters.length - 1);
+ var restProperty = ts.createPropertyAssignment(getParameterName(ts.last(parameters)), ts.createArrayLiteral(restArguments));
+ properties.push(restProperty);
+ }
+ var objectLiteral = ts.createObjectLiteral(properties, /*multiLine*/ false);
+ return objectLiteral;
+ }
+ function createNewParameters(functionDeclaration, program, host) {
+ var checker = program.getTypeChecker();
+ var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters);
+ var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration);
+ var objectParameterName = ts.createObjectBindingPattern(bindingElements);
+ var objectParameterType = createParameterTypeNode(refactorableParameters);
+ var objectInitializer;
+ // If every parameter in the original function was optional, add an empty object initializer to the new object parameter
+ if (ts.every(refactorableParameters, isOptionalParameter)) {
+ objectInitializer = ts.createObjectLiteral();
+ }
+ var objectParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, objectParameterName,
+ /*questionToken*/ undefined, objectParameterType, objectInitializer);
+ if (hasThisParameter(functionDeclaration.parameters)) {
+ var thisParameter = functionDeclaration.parameters[0];
+ var newThisParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, thisParameter.name,
+ /*questionToken*/ undefined, thisParameter.type);
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.name);
+ copyComments(thisParameter.name, newThisParameter.name);
+ if (thisParameter.type) {
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.type);
+ copyComments(thisParameter.type, newThisParameter.type);
+ }
+ return ts.createNodeArray([newThisParameter, objectParameter]);
+ }
+ return ts.createNodeArray([objectParameter]);
+ function createBindingElementFromParameterDeclaration(parameterDeclaration) {
+ var element = ts.createBindingElement(
+ /*dotDotDotToken*/ undefined,
+ /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer);
+ ts.suppressLeadingAndTrailingTrivia(element);
+ if (parameterDeclaration.initializer && element.initializer) {
+ copyComments(parameterDeclaration.initializer, element.initializer);
+ }
+ return element;
+ }
+ function createParameterTypeNode(parameters) {
+ var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration);
+ var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */);
+ return typeNode;
+ }
+ function createPropertySignatureFromParameterDeclaration(parameterDeclaration) {
+ var parameterType = parameterDeclaration.type;
+ if (!parameterType && (parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration))) {
+ parameterType = getTypeNode(parameterDeclaration);
+ }
+ var propertySignature = ts.createPropertySignature(
+ /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType,
+ /*initializer*/ undefined);
+ ts.suppressLeadingAndTrailingTrivia(propertySignature);
+ copyComments(parameterDeclaration.name, propertySignature.name);
+ if (parameterDeclaration.type && propertySignature.type) {
+ copyComments(parameterDeclaration.type, propertySignature.type);
+ }
+ return propertySignature;
+ }
+ function getTypeNode(node) {
+ var type = checker.getTypeAtLocation(node);
+ return ts.getTypeNodeIfAccessible(type, node, program, host);
+ }
+ function isOptionalParameter(parameterDeclaration) {
+ if (ts.isRestParameter(parameterDeclaration)) {
+ var type = checker.getTypeAtLocation(parameterDeclaration);
+ return !checker.isTupleType(type);
+ }
+ return checker.isOptionalParameter(parameterDeclaration);
+ }
+ }
+ function copyComments(sourceNode, targetNode) {
+ var sourceFile = sourceNode.getSourceFile();
+ var text = sourceFile.text;
+ if (hasLeadingLineBreak(sourceNode, text)) {
+ ts.copyLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ else {
+ ts.copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ ts.copyTrailingComments(sourceNode, targetNode, sourceFile);
+ }
+ function hasLeadingLineBreak(node, text) {
+ var start = node.getFullStart();
+ var end = node.getStart();
+ for (var i = start; i < end; i++) {
+ if (text.charCodeAt(i) === 10 /* lineFeed */)
+ return true;
+ }
+ return false;
+ }
+ function getParameterName(paramDeclaration) {
+ return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name);
+ }
+ function getClassNames(constructorDeclaration) {
+ switch (constructorDeclaration.parent.kind) {
+ case 240 /* ClassDeclaration */:
+ var classDeclaration = constructorDeclaration.parent;
+ return [classDeclaration.name];
+ case 209 /* ClassExpression */:
+ var classExpression = constructorDeclaration.parent;
+ var variableDeclaration = constructorDeclaration.parent.parent;
+ var className = classExpression.name;
+ if (className)
+ return [className, variableDeclaration.name];
+ return [variableDeclaration.name];
+ }
+ }
+ function getFunctionNames(functionDeclaration) {
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return [functionDeclaration.name];
+ case 157 /* Constructor */:
+ var ctrKeyword = ts.findChildOfKind(functionDeclaration, 124 /* ConstructorKeyword */, functionDeclaration.getSourceFile());
+ if (functionDeclaration.parent.kind === 209 /* ClassExpression */) {
+ var variableDeclaration = functionDeclaration.parent.parent;
+ return [variableDeclaration.name, ctrKeyword];
+ }
+ return [ctrKeyword];
+ case 197 /* ArrowFunction */:
+ return [functionDeclaration.parent.name];
+ case 196 /* FunctionExpression */:
+ if (functionDeclaration.name)
+ return [functionDeclaration.name, functionDeclaration.parent.name];
+ return [functionDeclaration.parent.name];
+ default:
+ return ts.Debug.assertNever(functionDeclaration);
+ }
+ }
+ })(convertParamsToDestructuredObject = refactor.convertParamsToDestructuredObject || (refactor.convertParamsToDestructuredObject = {}));
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
var ts;
(function (ts) {
/** The version of the language service API */
@@ -117611,7 +120170,8 @@
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
- this.transformFlags = undefined; // TODO: GH#18217
+ this.modifierFlagsCache = 0 /* None */;
+ this.transformFlags = 0 /* None */;
this.parent = undefined;
this.kind = kind;
}
@@ -117673,7 +120233,7 @@
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 288 /* FirstJSDocNode */ || kid.kind > 310 /* LastJSDocNode */; });
return child.kind < 148 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -117743,11 +120303,11 @@
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(311 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
- for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) {
- var node = nodes_7[_i];
+ for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
+ var node = nodes_1[_i];
addSyntheticNodes(list._children, pos, node.pos, parent);
list._children.push(node);
pos = node.end;
@@ -117761,6 +120321,8 @@
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
+ this.modifierFlagsCache = 0 /* None */;
+ this.transformFlags = 0 /* None */;
this.parent = undefined;
}
TokenOrIdentifierObject.prototype.getSourceFile = function () {
@@ -117989,8 +120551,8 @@
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_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)
@@ -118336,7 +120898,7 @@
var sourceFile;
if (this.currentFileName !== fileName) {
// This is a new file, just parse it
- sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 6 /* Latest */, version, /*setNodeParents*/ true, scriptKind);
+ sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 7 /* Latest */, version, /*setNodeParents*/ true, scriptKind);
}
else if (this.currentFileVersion !== version) {
// This is the same file, just a newer version. Incrementally parse the file.
@@ -118460,9 +121022,9 @@
}());
ts.ThrottledCancellationToken = ThrottledCancellationToken;
function createLanguageService(host, documentRegistry, syntaxOnly) {
+ var _a;
if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); }
if (syntaxOnly === void 0) { syntaxOnly = false; }
- var _a;
var syntaxTreeCache = new SyntaxTreeCache(host);
var program;
var lastProjectVersion;
@@ -118493,7 +121055,7 @@
function getValidSourceFile(fileName) {
var sourceFile = program.getSourceFile(fileName);
if (!sourceFile) {
- throw new Error("Could not find file: '" + fileName + "'.");
+ throw new Error("Could not find sourceFile: '" + fileName + "' in " + (program && JSON.stringify(program.getSourceFiles().map(function (f) { return f.fileName; }))) + ".");
}
return sourceFile;
}
@@ -118742,14 +121304,14 @@
var typeChecker = program.getTypeChecker();
var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker);
if (!symbol || typeChecker.isUnknownSymbol(symbol)) {
- var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined;
- return type_7 && {
+ 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_7, ts.getContainerNode(node)); }),
- documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined,
- tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined
+ 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) {
@@ -121158,6 +123720,7 @@
CommandTypes["SynchronizeProjectList"] = "synchronizeProjectList";
/* @internal */
CommandTypes["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles";
+ CommandTypes["UpdateOpen"] = "updateOpen";
/* @internal */
CommandTypes["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full";
/* @internal */
@@ -121875,8 +124438,8 @@
dts: 0, dtsSize: 0,
deferred: 0, deferredSize: 0,
};
- for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) {
- var info = infos_2[_i];
+ for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
+ var info = infos_1[_i];
var fileSize = includeSizes ? info.getTelemetryFileSize() : 0;
switch (info.scriptKind) {
case 1 /* JS */:
@@ -121936,7 +124499,8 @@
server.isScriptInfo = isScriptInfo;
var Project = /** @class */ (function () {
/*@internal*/
- function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) {
+ function Project(
+ /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) {
var _this = this;
this.projectName = projectName;
this.projectKind = projectKind;
@@ -122668,8 +125232,8 @@
var sourceFiles = this.program.getSourceFiles();
var strBuilder = "\tFiles (" + sourceFiles.length + ")\n";
if (writeProjectFileNames) {
- for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
- var file = sourceFiles_7[_i];
+ for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
+ var file = sourceFiles_1[_i];
strBuilder += "\t" + file.fileName + "\n";
}
}
@@ -122764,7 +125328,7 @@
// ../../.. 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_27 = function (globalPluginName) {
+ var _loop_1 = function (globalPluginName) {
// Skip empty names from odd commandline parses
if (!globalPluginName)
return "continue";
@@ -122772,14 +125336,14 @@
if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; }))
return "continue";
// 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, pluginConfigOverrides);
+ this_1.projectService.logger.info("Loading global plugin " + globalPluginName);
+ this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides);
};
- var this_2 = this;
+ var this_1 = 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_27(globalPluginName);
+ _loop_1(globalPluginName);
}
}
};
@@ -123014,7 +125578,6 @@
}
this.projectService.sendProjectLoadingFinishEvent(this);
this.projectService.sendProjectTelemetry(this);
- this.projectService.sendSurveyReady(this);
return result;
};
/*@internal*/
@@ -123156,18 +125719,18 @@
var ExternalProject = /** @class */ (function (_super) {
__extends(ExternalProject, _super);
/*@internal*/
- function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath) {
+ function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, pluginConfigOverrides) {
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 = [];
+ _this.enableGlobalPlugins(_this.getCompilerOptions(), pluginConfigOverrides);
return _this;
}
ExternalProject.prototype.updateGraph = function () {
var result = _super.prototype.updateGraph.call(this);
this.projectService.sendProjectTelemetry(this);
- this.projectService.sendSurveyReady(this);
return result;
};
ExternalProject.prototype.getExcludedFiles = function () {
@@ -123199,7 +125762,6 @@
server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground";
server.ProjectLoadingStartEvent = "projectLoadingStart";
server.ProjectLoadingFinishEvent = "projectLoadingFinish";
- server.SurveyReady = "surveyReady";
server.LargeFileReferencedEvent = "largeFileReferenced";
server.ConfigFileDiagEvent = "configFileDiag";
server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
@@ -123439,8 +126001,6 @@
this.pendingEnsureProjectForOpenFiles = false;
/** Tracks projects that we have already sent telemetry for. */
this.seenProjects = ts.createMap();
- /** Tracks projects that we have already sent survey events for. */
- this.seenSurveyProjects = ts.createMap();
this.host = opts.host;
this.logger = opts.logger;
this.cancellationToken = opts.cancellationToken;
@@ -123616,13 +126176,6 @@
this.eventHandler(event);
};
/* @internal */
- ProjectService.prototype.sendSurveyReadyEvent = function (surveyId) {
- if (!this.eventHandler) {
- return;
- }
- this.eventHandler({ eventName: server.SurveyReady, data: { surveyId: surveyId } });
- };
- /* @internal */
ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) {
if (!this.eventHandler) {
return;
@@ -123775,7 +126328,7 @@
};
ProjectService.prototype.getPreferences = function (file) {
var info = this.getScriptInfoForNormalizedPath(file);
- return info && info.getPreferences() || this.hostConfiguration.preferences;
+ return __assign({}, this.hostConfiguration.preferences, info && info.getPreferences());
};
ProjectService.prototype.getHostFormatCodeOptions = function () {
return this.hostConfiguration.formatCodeOptions;
@@ -123863,7 +126416,7 @@
return this.watchFactory.watchDirectory(this.host, directory, function (fileOrDirectory) {
var fileOrDirectoryPath = _this.toPath(fileOrDirectory);
project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
var configFilename = project.getConfigFilePath();
// If the the added or created file or directory is not supported file name, ignore the file
@@ -123963,7 +126516,7 @@
}
project.updateGraph();
if (!this.useSingleInferredProject && !project.projectRootPath) {
- var _loop_28 = function (inferredProject) {
+ var _loop_2 = function (inferredProject) {
if (inferredProject === project || inferredProject.isOrphan()) {
return "continue";
}
@@ -123984,17 +126537,27 @@
// 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_28(inferredProject);
+ _loop_2(inferredProject);
}
}
return project;
};
+ ProjectService.prototype.assignOrphanScriptInfosToInferredProject = function () {
+ var _this = this;
+ // 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);
+ }
+ });
+ };
/**
* 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;
+ ProjectService.prototype.closeOpenFile = function (info, skipAssignOrphanScriptInfosToInferredProject) {
// 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.
@@ -124033,15 +126596,8 @@
}
}
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);
- }
- });
+ if (!skipAssignOrphanScriptInfosToInferredProject && ensureProjectsForOpenFiles) {
+ this.assignOrphanScriptInfosToInferredProject();
}
// 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,
@@ -124054,6 +126610,7 @@
else {
this.handleDeletedFile(info);
}
+ return ensureProjectsForOpenFiles;
};
ProjectService.prototype.deleteScriptInfo = function (info) {
this.filenameToScriptInfo.delete(info.path);
@@ -124358,8 +126915,8 @@
this.projectToSizeMap.set(name, 0);
this.projectToSizeMap.forEach(function (val) { return (availableSpace -= (val || 0)); });
var totalNonTsFileSize = 0;
- for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) {
- var f = fileNames_2[_i];
+ for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
+ var f = fileNames_1[_i];
var fileName = propertyReader.getFileName(f);
if (ts.hasTSFileExtension(fileName)) {
continue;
@@ -124389,25 +126946,14 @@
ProjectService.prototype.createExternalProject = function (projectFileName, files, options, typeAcquisition, excludedFiles) {
var compilerOptions = convertCompilerOptions(options);
var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions,
- /*lastFileExceededProgramSize*/ this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave);
+ /*lastFileExceededProgramSize*/ this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave,
+ /*projectFilePath*/ undefined, this.currentPluginConfigOverrides);
project.excludedFiles = excludedFiles;
this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition);
this.externalProjects.push(project);
return project;
};
/*@internal*/
- ProjectService.prototype.sendSurveyReady = function (project) {
- if (this.seenSurveyProjects.has(project.projectName)) {
- return;
- }
- if (project.getCompilerOptions().checkJs !== undefined) {
- var name = "checkJs";
- this.logger.info("Survey " + name + " is ready");
- this.sendSurveyReadyEvent(name);
- this.seenSurveyProjects.set(project.projectName, true);
- }
- };
- /*@internal*/
ProjectService.prototype.sendProjectTelemetry = function (project) {
if (this.seenProjects.has(project.projectName)) {
setProjectOptionsUsed(project);
@@ -124536,8 +127082,8 @@
ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) {
var projectRootFilesMap = project.getRootFilesMap();
var newRootScriptInfoMap = ts.createMap();
- for (var _i = 0, files_4 = files; _i < files_4.length; _i++) {
- var f = files_4[_i];
+ for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
+ var f = files_1[_i];
var newRootFile = propertyReader.getFileName(f);
var normalizedPath = server.toNormalizedPath(newRootFile);
var isDynamic = server.isDynamicFileName(normalizedPath);
@@ -124755,7 +127301,7 @@
return projects;
function combineProjects(toAddInfo) {
if (toAddInfo !== info) {
- var _loop_29 = function (project) {
+ var _loop_3 = function (project) {
// Add the projects only if they can use symLink targets and not already in the list
if (project.languageServiceEnabled &&
!project.isOrphan() &&
@@ -124772,7 +127318,7 @@
};
for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) {
var project = _a[_i];
- _loop_29(project);
+ _loop_3(project);
}
}
}
@@ -124806,7 +127352,7 @@
var watchDir = dir + "/node_modules";
var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) {
var fileOrDirectoryPath = _this.toPath(fileOrDirectory);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
// Has extension
ts.Debug.assert(result.refCount > 0);
@@ -125275,18 +127821,21 @@
return proj.containsScriptInfo(info);
});
};
- ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
- var configFileName;
- var configFileErrors;
+ ProjectService.prototype.getOrCreateOpenScriptInfo = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); // TODO: GH#18217
this.openFiles.set(info.path, projectRootPath);
+ return info;
+ };
+ ProjectService.prototype.assignProjectToOpenedScriptInfo = function (info) {
+ var configFileName;
+ var configFileErrors;
var project = this.findExternalProjectContainingOpenScriptInfo(info);
if (!project && !this.syntaxOnly) { // Checking syntaxOnly is an optimization
configFileName = this.getConfigFileNameForFile(info);
if (configFileName) {
project = this.findConfiguredProjectByProjectName(configFileName);
if (!project) {
- project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + fileName + " to open");
+ project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + info.fileName + " to open");
// 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
@@ -125294,7 +127843,7 @@
}
else {
configFileErrors = project.getAllProjectErrors();
- this.sendConfigFileDiagEvent(project, fileName);
+ this.sendConfigFileDiagEvent(project, info.fileName);
}
}
else {
@@ -125313,9 +127862,13 @@
// 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(this.openFiles.has(info.path));
+ this.assignOrphanScriptInfoToInferredProject(info, this.openFiles.get(info.path));
}
ts.Debug.assert(!info.isOrphan());
+ return { configFileName: configFileName, configFileErrors: configFileErrors };
+ };
+ ProjectService.prototype.cleanupAfterOpeningFile = function () {
// 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();
@@ -125333,8 +127886,13 @@
// the file from that old project is reopened because of opening file from here.
this.removeOrphanScriptInfos();
this.printProjects();
+ };
+ ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
+ var info = this.getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath);
+ var result = this.assignProjectToOpenedScriptInfo(info);
+ this.cleanupAfterOpeningFile();
this.telemetryOnOpenFile(info);
- return { configFileName: configFileName, configFileErrors: configFileErrors };
+ return result;
};
ProjectService.prototype.removeOrphanConfiguredProjects = function () {
var _this = this;
@@ -125430,25 +127988,22 @@
var info = { checkJs: !!project.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) {
+ ProjectService.prototype.closeClientFile = function (uncheckedFileName, skipAssignOrphanScriptInfosToInferredProject) {
var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName));
- if (info) {
- this.closeOpenFile(info);
- }
+ var result = info ? this.closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) : false;
+ if (!skipAssignOrphanScriptInfosToInferredProject) {
this.printProjects();
+ }
+ return result;
};
ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) {
- var _loop_30 = function (proj) {
+ var _loop_4 = 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_30(proj);
+ _loop_4(proj);
}
};
/* @internal */
@@ -125461,35 +128016,59 @@
};
/* @internal */
ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) {
+ var _this = this;
+ var openScriptInfos;
+ var assignOrphanScriptInfosToInferredProject = false;
if (openFiles) {
- for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) {
- var file = openFiles_1[_i];
+ while (true) {
+ var _a = openFiles.next(), file = _a.value, done = _a.done;
+ if (done)
+ break;
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); // TODO: GH#18217
+ // Create script infos so we have the new content for all the open files before we do any updates to projects
+ var info = this.getOrCreateOpenScriptInfo(scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName), file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent, file.projectRootPath ? server.toNormalizedPath(file.projectRootPath) : undefined);
+ (openScriptInfos || (openScriptInfos = [])).push(info);
}
}
if (changedFiles) {
- for (var _a = 0, changedFiles_2 = changedFiles; _a < changedFiles_2.length; _a++) {
- var file = changedFiles_2[_a];
+ while (true) {
+ var _b = changedFiles.next(), file = _b.value, done = _b.done;
+ if (done)
+ break;
var scriptInfo = this.getScriptInfo(file.fileName);
ts.Debug.assert(!!scriptInfo);
+ // Make edits to script infos and marks containing project as dirty
this.applyChangesToFile(scriptInfo, file.changes);
}
}
if (closedFiles) {
- for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) {
- var file = closedFiles_1[_b];
- this.closeClientFile(file);
- }
- }
+ for (var _i = 0, closedFiles_1 = closedFiles; _i < closedFiles_1.length; _i++) {
+ var file = closedFiles_1[_i];
+ // Close files, but dont assign projects to orphan open script infos, that part comes later
+ assignOrphanScriptInfosToInferredProject = this.closeClientFile(file, /*skipAssignOrphanScriptInfosToInferredProject*/ true) || assignOrphanScriptInfosToInferredProject;
+ }
+ }
+ // All the script infos now exist, so ok to go update projects for open files
+ if (openScriptInfos) {
+ openScriptInfos.forEach(function (info) { return _this.assignProjectToOpenedScriptInfo(info); });
+ }
+ // While closing files there could be open files that needed assigning new inferred projects, do it now
+ if (assignOrphanScriptInfosToInferredProject) {
+ this.assignOrphanScriptInfosToInferredProject();
+ }
+ // Cleanup projects
+ this.cleanupAfterOpeningFile();
+ // Telemetry
+ ts.forEach(openScriptInfos, function (info) { return _this.telemetryOnOpenFile(info); });
+ this.printProjects();
};
/* @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];
+ while (true) {
+ var _a = changes.next(), change = _a.value, done = _a.done;
+ if (done)
+ break;
scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText);
}
};
@@ -125558,12 +128137,12 @@
var excludeRules = [];
var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); });
var excludedFiles = [];
- var _loop_31 = function (name) {
- var rule = this_3.safelist[name];
+ var _loop_5 = function (name) {
+ var rule = this_2.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_3.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'");
+ this_2.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++) {
@@ -125576,7 +128155,7 @@
}
}
if (rule.exclude) {
- var _loop_33 = function (exclude) {
+ var _loop_7 = function (exclude) {
var processedRule = root.replace(rule.match, function () {
var groups = [];
for (var _i = 0; _i < arguments.length; _i++) {
@@ -125603,7 +128182,7 @@
};
for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) {
var exclude = _d[_c];
- _loop_33(exclude);
+ _loop_7(exclude);
}
}
else {
@@ -125616,14 +128195,14 @@
}
}
};
- var this_3 = this;
+ var this_2 = this;
for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) {
var name = _a[_i];
- _loop_31(name);
+ _loop_5(name);
}
var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); });
var filesToKeep = [];
- var _loop_32 = function (i) {
+ var _loop_6 = function (i) {
if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) {
excludedFiles.push(normalizedNames[i]);
}
@@ -125634,9 +128213,9 @@
if (ts.fileExtensionIs(baseName, "js")) {
var inferredTypingName = ts.removeFileExtension(baseName);
var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
- var typeName = this_4.legacySafelist.get(cleanedTypingName);
+ var typeName = this_3.legacySafelist.get(cleanedTypingName);
if (typeName !== undefined) {
- this_4.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist");
+ this_3.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist");
excludedFiles.push(normalizedNames[i]);
// *exclude* it from the project...
exclude = true;
@@ -125659,9 +128238,9 @@
}
}
};
- var this_4 = this;
+ var this_3 = this;
for (var i = 0; i < proj.rootFiles.length; i++) {
- _loop_32(i);
+ _loop_6(i);
}
proj.rootFiles = filesToKeep;
return excludedFiles;
@@ -126066,7 +128645,7 @@
var outputs = [];
combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, getMappedLocation) {
var project = _a.project, location = _a.location;
- var _loop_34 = function (outputReferencedSymbol) {
+ var _loop_8 = function (outputReferencedSymbol) {
var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition));
var definition = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : __assign({}, outputReferencedSymbol.definition, { textSpan: ts.createTextSpan(mappedDefinitionFile.pos, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName });
var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); });
@@ -126084,7 +128663,7 @@
};
for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.pos) || server.emptyArray; _i < _b.length; _i++) {
var outputReferencedSymbol = _b[_i];
- _loop_34(outputReferencedSymbol);
+ _loop_8(outputReferencedSymbol);
}
}, function () { return getDefinitionLocation(defaultProject, initialLocation); });
return outputs.filter(function (o) { return o.references.length !== 0; });
@@ -126175,8 +128754,8 @@
}
var Session = /** @class */ (function () {
function Session(opts) {
- var _a;
var _this = this;
+ var _a;
this.changeSeq = 0;
this.handlers = ts.createMapFromTemplate((_a = {},
_a[server.CommandNames.Status] = function () {
@@ -126216,9 +128795,31 @@
});
return _this.requiredResponse(converted);
},
+ _a[server.CommandNames.UpdateOpen] = function (request) {
+ _this.changeSeq++;
+ _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles && ts.mapIterator(ts.arrayIterator(request.arguments.openFiles), function (file) { return ({
+ fileName: file.file,
+ content: file.fileContent,
+ scriptKind: file.scriptKindName,
+ projectRootPath: file.projectRootPath
+ }); }), request.arguments.changedFiles && ts.mapIterator(ts.arrayIterator(request.arguments.changedFiles), function (file) { return ({
+ fileName: file.fileName,
+ changes: ts.mapDefinedIterator(ts.arrayReverseIterator(file.textChanges), function (change) {
+ var scriptInfo = ts.Debug.assertDefined(_this.projectService.getScriptInfo(file.fileName));
+ var start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset);
+ var end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset);
+ return start >= 0 ? { span: { start: start, length: end - start }, newText: change.newText } : undefined;
+ })
+ }); }), request.arguments.closedFiles);
+ return _this.requiredResponse(/*response*/ true);
+ },
_a[server.CommandNames.ApplyChangedToOpenFiles] = function (request) {
_this.changeSeq++;
- _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); // TODO: GH#18217
+ _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles && ts.arrayIterator(request.arguments.openFiles), request.arguments.changedFiles && ts.mapIterator(ts.arrayIterator(request.arguments.changedFiles), function (file) { return ({
+ fileName: file.fileName,
+ // apply changes in reverse order
+ changes: ts.arrayReverseIterator(file.changes)
+ }); }), request.arguments.closedFiles);
// TODO: report errors
return _this.requiredResponse(/*response*/ true);
},
@@ -126483,6 +129084,7 @@
},
_a[server.CommandNames.ConfigurePlugin] = function (request) {
_this.configurePlugin(request.arguments);
+ _this.doOutput(/*info*/ undefined, server.CommandNames.ConfigurePlugin, request.seq, /*success*/ true);
return _this.notRequired();
},
_a));
@@ -126557,10 +129159,6 @@
diagnostics: bakedDiags
}, server.ConfigFileDiagEvent);
break;
- case server.SurveyReady:
- var surveyId = event.data.surveyId;
- this.event({ surveyId: surveyId }, server.SurveyReady);
- break;
case server.ProjectLanguageServiceStateEvent: {
var eventName = server.ProjectLanguageServiceStateEvent;
this.event({
@@ -126605,7 +129203,8 @@
msg += "\n" + server.indent(err.stack);
}
}
- if (fileRequest && this.logger.hasLevel(server.LogLevel.verbose)) {
+ if (this.logger.hasLevel(server.LogLevel.verbose)) {
+ if (fileRequest) {
try {
var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project;
var scriptInfo = project.getScriptInfoForNormalizedPath(file);
@@ -126616,6 +129215,20 @@
}
catch (_b) { } // tslint:disable-line no-empty
}
+ if (err.message && err.message.indexOf("Could not find sourceFile:") !== -1) {
+ msg += "\n\nProjects::\n";
+ var counter_1 = 0;
+ var addProjectInfo = function (project) {
+ msg += "\nProject '" + project.projectName + "' (" + server.ProjectKind[project.projectKind] + ") " + counter_1 + "\n";
+ msg += project.filesToString(/*writeProjectFileNames*/ true);
+ msg += "\n-----------------------------------------------\n";
+ counter_1++;
+ };
+ this.projectService.externalProjects.forEach(addProjectInfo);
+ this.projectService.configuredProjects.forEach(addProjectInfo);
+ this.projectService.inferredProjects.forEach(addProjectInfo);
+ }
+ }
this.logger.msg(msg, server.Msg.Err);
};
Session.prototype.send = function (msg) {
@@ -127048,8 +129661,7 @@
Session.prototype.getRenameInfo = function (args) {
var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
var position = this.getPositionInFile(args, file);
- var preferences = this.getHostPreferences();
- return project.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: preferences.allowRenameOfImportPath });
+ return project.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath });
};
Session.prototype.getProjects = function (args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) {
var projects;
@@ -127095,11 +129707,11 @@
var file = server.toNormalizedPath(args.file);
var position = this.getPositionInFile(args, file);
var projects = this.getProjects(args);
- var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, this.getHostPreferences());
+ var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, this.getPreferences(file));
if (!simplifiedResult)
return locations;
var defaultProject = this.getDefaultProject(args);
- var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getHostPreferences().allowRenameOfImportPath }), ts.Debug.assertDefined(this.projectService.getScriptInfo(file)));
+ var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath }), ts.Debug.assertDefined(this.projectService.getScriptInfo(file)));
return { info: renameInfo, locs: this.toSpanGroups(locations) };
};
Session.prototype.mapRenameInfo = function (info, scriptInfo) {
@@ -127116,11 +129728,11 @@
for (var _i = 0, locations_1 = locations; _i < locations_1.length; _i++) {
var _a = locations_1[_i];
var fileName = _a.fileName, textSpan = _a.textSpan, _ = _a.originalTextSpan, _1 = _a.originalFileName, prefixSuffixText = __rest(_a, ["fileName", "textSpan", "originalTextSpan", "originalFileName"]);
- var group_2 = map.get(fileName);
- if (!group_2)
- map.set(fileName, group_2 = { file: fileName, locs: [] });
+ var group_1 = map.get(fileName);
+ if (!group_1)
+ map.set(fileName, group_1 = { file: fileName, locs: [] });
var scriptInfo = ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName));
- group_2.locs.push(__assign({}, this.toLocationTextSpan(textSpan, scriptInfo), prefixSuffixText));
+ group_1.locs.push(__assign({}, this.toLocationTextSpan(textSpan, scriptInfo), prefixSuffixText));
}
return ts.arrayFrom(map.values());
};
@@ -127137,7 +129749,7 @@
var symbolDisplayString = nameInfo ? ts.displayPartsToString(nameInfo.displayParts) : "";
var nameSpan = nameInfo && nameInfo.textSpan;
var symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0;
- var symbolName_3 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : "";
+ 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;
@@ -127148,7 +129760,7 @@
return __assign({}, toFileSpan(fileName, textSpan, scriptInfo), { lineText: lineText, isWriteAccess: isWriteAccess, isDefinition: isDefinition });
});
});
- var result = { refs: refs, symbolName: symbolName_3, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString };
+ var result = { refs: refs, symbolName: symbolName_1, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString };
return result;
}
else {
@@ -127360,10 +129972,10 @@
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 name = entry.name, kind_1 = 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 };
+ return { name: name, kind: kind_1, 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 */) {
@@ -127468,10 +130080,10 @@
var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
if (start >= 0) {
this.changeSeq++;
- this.projectService.applyChangesToFile(scriptInfo, [{
+ this.projectService.applyChangesToFile(scriptInfo, ts.singleIterator({
span: { start: start, length: end - start },
newText: args.insertString // TODO: GH#18217
- }]);
+ }));
}
};
Session.prototype.reload = function (args, reqSeq) {
@@ -127942,14 +130554,14 @@
}
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_4 = _a.textChanges;
+ for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
+ var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges;
if (fileName !== textFilename) {
continue;
}
- 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_6 = _c.length;
- text = text.slice(0, start) + newText + text.slice(start + length_6);
+ 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);
}
}
return text;
@@ -128717,4 +131329,5 @@
}());
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
-//# sourceMappingURL=tsserverlibrary.out.js.map
\ No newline at end of file
+
+//# sourceMappingURL=tsserverlibrary.js.map

lib/typescript.d.ts

@@ -14,7 +14,7 @@
***************************************************************************** */
declare namespace ts {
- const versionMajorMinor = "3.3";
+ const versionMajorMinor = "3.4";
/** The version of the TypeScript compiler release */
const version: string;
}
@@ -355,40 +355,45 @@
ShorthandPropertyAssignment = 276,
SpreadAssignment = 277,
EnumMember = 278,
- SourceFile = 279,
- Bundle = 280,
- UnparsedSource = 281,
- InputFiles = 282,
- JSDocTypeExpression = 283,
- JSDocAllType = 284,
- JSDocUnknownType = 285,
- JSDocNullableType = 286,
- JSDocNonNullableType = 287,
- JSDocOptionalType = 288,
- JSDocFunctionType = 289,
- JSDocVariadicType = 290,
- JSDocComment = 291,
- JSDocTypeLiteral = 292,
- JSDocSignature = 293,
- JSDocTag = 294,
- JSDocAugmentsTag = 295,
- JSDocClassTag = 296,
- JSDocCallbackTag = 297,
- JSDocEnumTag = 298,
- JSDocParameterTag = 299,
- JSDocReturnTag = 300,
- JSDocThisTag = 301,
- JSDocTypeTag = 302,
- JSDocTemplateTag = 303,
- JSDocTypedefTag = 304,
- JSDocPropertyTag = 305,
- SyntaxList = 306,
- NotEmittedStatement = 307,
- PartiallyEmittedExpression = 308,
- CommaListExpression = 309,
- MergeDeclarationMarker = 310,
- EndOfDeclarationMarker = 311,
- Count = 312,
+ UnparsedPrologue = 279,
+ UnparsedPrepend = 280,
+ UnparsedText = 281,
+ UnparsedInternalText = 282,
+ UnparsedSyntheticReference = 283,
+ SourceFile = 284,
+ Bundle = 285,
+ UnparsedSource = 286,
+ InputFiles = 287,
+ JSDocTypeExpression = 288,
+ JSDocAllType = 289,
+ JSDocUnknownType = 290,
+ JSDocNullableType = 291,
+ JSDocNonNullableType = 292,
+ JSDocOptionalType = 293,
+ JSDocFunctionType = 294,
+ JSDocVariadicType = 295,
+ JSDocComment = 296,
+ JSDocTypeLiteral = 297,
+ JSDocSignature = 298,
+ JSDocTag = 299,
+ JSDocAugmentsTag = 300,
+ JSDocClassTag = 301,
+ JSDocCallbackTag = 302,
+ JSDocEnumTag = 303,
+ JSDocParameterTag = 304,
+ JSDocReturnTag = 305,
+ JSDocThisTag = 306,
+ JSDocTypeTag = 307,
+ JSDocTemplateTag = 308,
+ JSDocTypedefTag = 309,
+ JSDocPropertyTag = 310,
+ SyntaxList = 311,
+ NotEmittedStatement = 312,
+ PartiallyEmittedExpression = 313,
+ CommaListExpression = 314,
+ MergeDeclarationMarker = 315,
+ EndOfDeclarationMarker = 316,
+ Count = 317,
FirstAssignment = 59,
LastAssignment = 71,
FirstCompoundAssignment = 60,
@@ -414,10 +419,10 @@
FirstBinaryOperator = 28,
LastBinaryOperator = 71,
FirstNode = 148,
- FirstJSDocNode = 283,
- LastJSDocNode = 305,
- FirstJSDocTagNode = 294,
- LastJSDocTagNode = 305
+ FirstJSDocNode = 288,
+ LastJSDocNode = 310,
+ FirstJSDocTagNode = 299,
+ LastJSDocTagNode = 310,
}
enum NodeFlags {
None = 0,
@@ -446,7 +451,7 @@
ReachabilityCheckFlags = 384,
ReachabilityAndEmitFlags = 1408,
ContextFlags = 12679168,
- TypeExcludesFlags = 20480
+ TypeExcludesFlags = 20480,
}
enum ModifierFlags {
None = 0,
@@ -814,7 +819,7 @@
}
interface TypeOperatorNode extends TypeNode {
kind: SyntaxKind.TypeOperator;
- operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword;
+ operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword;
type: TypeNode;
}
interface IndexedAccessTypeNode extends TypeNode {
@@ -997,6 +1002,14 @@
interface NoSubstitutionTemplateLiteral extends LiteralExpression {
kind: SyntaxKind.NoSubstitutionTemplateLiteral;
}
+ enum TokenFlags {
+ None = 0,
+ Scientific = 16,
+ Octal = 32,
+ HexSpecifier = 64,
+ BinarySpecifier = 128,
+ OctalSpecifier = 256,
+ }
interface NumericLiteral extends LiteralExpression {
kind: SyntaxKind.NumericLiteral;
}
@@ -1190,9 +1203,9 @@
dotDotDotToken?: Token<SyntaxKind.DotDotDotToken>;
expression?: Expression;
}
- interface JsxText extends Node {
+ interface JsxText extends LiteralLikeNode {
kind: SyntaxKind.JsxText;
- containsOnlyWhiteSpaces: boolean;
+ containsOnlyTriviaWhiteSpaces: boolean;
parent: JsxElement;
}
type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment;
@@ -1737,10 +1750,44 @@
}
interface UnparsedSource extends Node {
kind: SyntaxKind.UnparsedSource;
- fileName?: string;
+ fileName: string;
text: string;
+ prologues: ReadonlyArray<UnparsedPrologue>;
+ helpers: ReadonlyArray<UnscopedEmitHelper> | undefined;
+ referencedFiles: ReadonlyArray<FileReference>;
+ typeReferenceDirectives: ReadonlyArray<string> | undefined;
+ libReferenceDirectives: ReadonlyArray<FileReference>;
+ hasNoDefaultLib?: boolean;
sourceMapPath?: string;
sourceMapText?: string;
+ syntheticReferences?: ReadonlyArray<UnparsedSyntheticReference>;
+ texts: ReadonlyArray<UnparsedSourceText>;
+ }
+ type UnparsedSourceText = UnparsedPrepend | UnparsedTextLike;
+ type UnparsedNode = UnparsedPrologue | UnparsedSourceText | UnparsedSyntheticReference;
+ interface UnparsedSection extends Node {
+ kind: SyntaxKind;
+ data?: string;
+ parent: UnparsedSource;
+ }
+ interface UnparsedPrologue extends UnparsedSection {
+ kind: SyntaxKind.UnparsedPrologue;
+ data: string;
+ parent: UnparsedSource;
+ }
+ interface UnparsedPrepend extends UnparsedSection {
+ kind: SyntaxKind.UnparsedPrepend;
+ data: string;
+ parent: UnparsedSource;
+ texts: ReadonlyArray<UnparsedTextLike>;
+ }
+ interface UnparsedTextLike extends UnparsedSection {
+ kind: SyntaxKind.UnparsedText | SyntaxKind.UnparsedInternalText;
+ parent: UnparsedSource;
+ }
+ interface UnparsedSyntheticReference extends UnparsedSection {
+ kind: SyntaxKind.UnparsedSyntheticReference;
+ parent: UnparsedSource;
}
interface JsonSourceFile extends SourceFile {
statements: NodeArray<JsonObjectExpressionStatement>;
@@ -2014,7 +2061,7 @@
WriteTypeParametersOrArguments = 1,
UseOnlyExternalAliasing = 2,
AllowAnyNodeKind = 4,
- UseAliasDefinedOutsideCurrentScope = 8
+ UseAliasDefinedOutsideCurrentScope = 8,
}
enum TypePredicateKind {
This = 0,
@@ -2092,7 +2139,7 @@
ExportHasLocal = 944,
BlockScoped = 418,
PropertyOrAccessor = 98308,
- ClassMember = 106500
+ ClassMember = 106500,
}
interface Symbol {
flags: SymbolFlags;
@@ -2200,7 +2247,7 @@
Instantiable = 63176704,
StructuredOrInstantiable = 66846720,
Narrowable = 133970943,
- NotUnionOrUnit = 67637251
+ NotUnionOrUnit = 67637251,
}
type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
interface Type {
@@ -2247,7 +2294,7 @@
MarkerType = 8192,
JSLiteral = 16384,
FreshLiteral = 32768,
- ClassOrInterface = 3
+ ClassOrInterface = 3,
}
interface ObjectType extends Type {
objectFlags: ObjectFlags;
@@ -2286,6 +2333,7 @@
interface TupleType extends GenericType {
minLength: number;
hasRestElement: boolean;
+ readonly: boolean;
associatedNames?: __String[];
}
interface TupleTypeReference extends TypeReference {
@@ -2334,8 +2382,8 @@
root: ConditionalRoot;
checkType: Type;
extendsType: Type;
- resolvedTrueType?: Type;
- resolvedFalseType?: Type;
+ trueType: Type;
+ falseType: Type;
}
interface SubstitutionType extends InstantiableType {
typeVariable: TypeVariable;
@@ -2494,6 +2542,8 @@
reactNamespace?: string;
jsxFactory?: string;
composite?: boolean;
+ incremental?: boolean;
+ tsBuildInfoFile?: string;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -2570,9 +2620,10 @@
ES2016 = 3,
ES2017 = 4,
ES2018 = 5,
- ESNext = 6,
+ ES2019 = 6,
+ ESNext = 7,
JSON = 100,
- Latest = 6
+ Latest = 7
}
enum LanguageVariant {
Standard = 0,
@@ -2669,7 +2720,8 @@
Dts = ".d.ts",
Js = ".js",
Jsx = ".jsx",
- Json = ".json"
+ Json = ".json",
+ TsBuildInfo = ".tsbuildinfo"
}
interface ResolvedModuleWithFailedLookupLocations {
readonly resolvedModule: ResolvedModuleFull | undefined;
@@ -2742,7 +2794,7 @@
NoHoisting = 2097152,
HasEndOfDeclarationMarker = 4194304,
Iterator = 8388608,
- NoAsciiEscaping = 16777216
+ NoAsciiEscaping = 16777216,
}
interface EmitHelper {
readonly name: string;
@@ -2750,6 +2802,10 @@
readonly text: string | ((node: EmitHelperUniqueNameCallback) => string);
readonly priority?: number;
}
+ interface UnscopedEmitHelper extends EmitHelper {
+ readonly scoped: false;
+ readonly text: string;
+ }
type EmitHelperUniqueNameCallback = (name: string) => string;
enum EmitHint {
SourceFile = 0,
@@ -3359,6 +3415,7 @@
function isNewExpression(node: Node): node is NewExpression;
function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression;
function isTypeAssertion(node: Node): node is TypeAssertion;
+ function isConstTypeReference(node: Node): boolean;
function isParenthesizedExpression(node: Node): node is ParenthesizedExpression;
function skipPartiallyEmittedExpressions(node: Expression): Expression;
function skipPartiallyEmittedExpressions(node: Node): Node;
@@ -3448,6 +3505,9 @@
function isSourceFile(node: Node): node is SourceFile;
function isBundle(node: Node): node is Bundle;
function isUnparsedSource(node: Node): node is UnparsedSource;
+ function isUnparsedPrepend(node: Node): node is UnparsedPrepend;
+ function isUnparsedTextLike(node: Node): node is UnparsedTextLike;
+ function isUnparsedNode(node: Node): node is UnparsedNode;
function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression;
function isJSDocAllType(node: JSDocAllType): node is JSDocAllType;
function isJSDocUnknownType(node: Node): node is JSDocUnknownType;
@@ -3667,7 +3727,7 @@
function createLiteral(value: number | PseudoBigInt): NumericLiteral;
function createLiteral(value: boolean): BooleanLiteral;
function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression;
- function createNumericLiteral(value: string): NumericLiteral;
+ function createNumericLiteral(value: string, numericLiteralFlags?: TokenFlags): NumericLiteral;
function createBigIntLiteral(value: string): BigIntLiteral;
function createStringLiteral(text: string): StringLiteral;
function createRegularExpressionLiteral(text: string): RegularExpressionLiteral;
@@ -3759,7 +3819,7 @@
function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode;
function createThisTypeNode(): ThisTypeNode;
function createTypeOperatorNode(type: TypeNode): TypeOperatorNode;
- function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword, type: TypeNode): TypeOperatorNode;
+ function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword, type: TypeNode): TypeOperatorNode;
function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode;
function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
@@ -3932,6 +3992,10 @@
function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement;
function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement;
function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray<JsxChild>, closingFragment: JsxClosingFragment): JsxFragment;
+ function createJsxText(text: string, containsOnlyTriviaWhiteSpaces?: boolean): JsxText;
+ function updateJsxText(node: JsxText, text: string, containsOnlyTriviaWhiteSpaces?: boolean): JsxText;
+ function createJsxOpeningFragment(): JsxOpeningFragment;
+ function createJsxJsxClosingFragment(): JsxClosingFragment;
function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: ReadonlyArray<JsxChild>, closingFragment: JsxClosingFragment): JsxFragment;
function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute;
function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute;
@@ -3983,10 +4047,10 @@
function updateCommaList(node: CommaListExpression, elements: ReadonlyArray<Expression>): CommaListExpression;
function createBundle(sourceFiles: ReadonlyArray<SourceFile>, prepends?: ReadonlyArray<UnparsedSource | InputFiles>): Bundle;
function createUnparsedSourceFile(text: string): UnparsedSource;
- function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts"): UnparsedSource;
+ function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts", stripInternal?: boolean): UnparsedSource;
function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource;
function createInputFiles(javascriptText: string, declarationText: string): InputFiles;
- function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined): InputFiles;
+ function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined, buildInfoPath: string | undefined): InputFiles;
function createInputFiles(javascriptText: string, declarationText: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): InputFiles;
function updateBundle(node: Bundle, sourceFiles: ReadonlyArray<SourceFile>, prepends?: ReadonlyArray<UnparsedSource>): Bundle;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray<Statement>): CallExpression;

lib/typescript.js

@@ -73,9 +73,9 @@
(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.3";
+ ts.versionMajorMinor = "3.4";
/** The version of the TypeScript compiler release */
- ts.version = ts.versionMajorMinor + ".4000";
+ ts.version = ts.versionMajorMinor + ".5";
})(ts || (ts = {}));
(function (ts) {
/* @internal */
@@ -131,19 +131,25 @@
// Keep the class inside a function so it doesn't get compiled if it's not used.
function shimMap() {
var MapIterator = /** @class */ (function () {
- function MapIterator(data, selector) {
- this.index = 0;
- this.data = data;
+ function MapIterator(currentEntry, selector) {
+ this.currentEntry = currentEntry;
this.selector = selector;
- this.keys = Object.keys(data);
}
MapIterator.prototype.next = function () {
- var index = this.index;
- if (index < this.keys.length) {
- this.index++;
- return { value: this.selector(this.data, this.keys[index]), done: false };
+ // Navigate to the next entry.
+ while (this.currentEntry) {
+ var skipNext = !!this.currentEntry.skipNext;
+ this.currentEntry = this.currentEntry.nextEntry;
+ if (!skipNext) {
+ break;
+ }
}
+ if (this.currentEntry) {
+ return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false };
+ }
+ else {
return { value: undefined, done: true };
+ }
};
return MapIterator;
}());
@@ -151,15 +157,36 @@
function class_1() {
this.data = createDictionaryObject();
this.size = 0;
+ // Create a first (stub) map entry that will not contain a key
+ // and value but serves as starting point for iterators.
+ this.firstEntry = {};
+ // When the map is empty, the last entry is the same as the
+ // first one.
+ this.lastEntry = this.firstEntry;
}
class_1.prototype.get = function (key) {
- return this.data[key];
+ var entry = this.data[key];
+ return entry && entry.value;
};
class_1.prototype.set = function (key, value) {
if (!this.has(key)) {
this.size++;
+ // Create a new entry that will be appended at the
+ // end of the linked list.
+ var newEntry = {
+ key: key,
+ value: value
+ };
+ this.data[key] = newEntry;
+ // Adjust the references.
+ var previousLastEntry = this.lastEntry;
+ previousLastEntry.nextEntry = newEntry;
+ newEntry.previousEntry = previousLastEntry;
+ this.lastEntry = newEntry;
+ }
+ else {
+ this.data[key].value = value;
}
- this.data[key] = value;
return this;
};
class_1.prototype.has = function (key) {
@@ -169,7 +196,28 @@
class_1.prototype.delete = function (key) {
if (this.has(key)) {
this.size--;
+ var entry = this.data[key];
delete this.data[key];
+ // Adjust the linked list references of the neighbor entries.
+ var previousEntry = entry.previousEntry;
+ previousEntry.nextEntry = entry.nextEntry;
+ if (entry.nextEntry) {
+ entry.nextEntry.previousEntry = previousEntry;
+ }
+ // When the deleted entry was the last one, we need to
+ // adust the lastEntry reference.
+ if (this.lastEntry === entry) {
+ this.lastEntry = previousEntry;
+ }
+ // Adjust the forward reference of the deleted entry
+ // in case an iterator still references it. This allows us
+ // to throw away the entry, but when an active iterator
+ // (which points to the current entry) continues, it will
+ // navigate to the entry that originally came before the
+ // current one and skip it.
+ entry.previousEntry = undefined;
+ entry.nextEntry = previousEntry;
+ entry.skipNext = true;
return true;
}
return false;
@@ -177,24 +225,46 @@
class_1.prototype.clear = function () {
this.data = createDictionaryObject();
this.size = 0;
+ // Reset the linked list. Note that we must adjust the forward
+ // references of the deleted entries to ensure iterators stuck
+ // in the middle of the list don't continue with deleted entries,
+ // but can continue with new entries added after the clear()
+ // operation.
+ var firstEntry = this.firstEntry;
+ var currentEntry = firstEntry.nextEntry;
+ while (currentEntry) {
+ var nextEntry = currentEntry.nextEntry;
+ currentEntry.previousEntry = undefined;
+ currentEntry.nextEntry = firstEntry;
+ currentEntry.skipNext = true;
+ currentEntry = nextEntry;
+ }
+ firstEntry.nextEntry = undefined;
+ this.lastEntry = firstEntry;
};
class_1.prototype.keys = function () {
- return new MapIterator(this.data, function (_data, key) { return key; });
+ return new MapIterator(this.firstEntry, function (key) { return key; });
};
class_1.prototype.values = function () {
- return new MapIterator(this.data, function (data, key) { return data[key]; });
+ return new MapIterator(this.firstEntry, function (_key, value) { return value; });
};
class_1.prototype.entries = function () {
- return new MapIterator(this.data, function (data, key) { return [key, data[key]]; });
+ return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; });
};
class_1.prototype.forEach = function (action) {
- for (var key in this.data) {
- action(this.data[key], key);
+ var iterator = this.entries();
+ while (true) {
+ var _a = iterator.next(), entry = _a.value, done = _a.done;
+ if (done) {
+ break;
+ }
+ action(entry[1], entry[0]);
}
};
return class_1;
}());
}
+ ts.shimMap = shimMap;
function length(array) {
return array ? array.length : 0;
}
@@ -742,7 +812,7 @@
}
/**
* Deduplicates an unsorted array.
- * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates.
+ * @param equalityComparer An `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`.
*/
@@ -958,6 +1028,21 @@
} };
}
ts.arrayIterator = arrayIterator;
+ function arrayReverseIterator(array) {
+ var i = array.length;
+ return {
+ next: function () {
+ if (i === 0) {
+ return { value: undefined, done: true };
+ }
+ else {
+ i--;
+ return { value: array[i], done: false };
+ }
+ }
+ };
+ }
+ ts.arrayReverseIterator = arrayReverseIterator;
/**
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
*/
@@ -1168,9 +1253,11 @@
}
for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
var arg = args_1[_a];
+ if (arg === undefined)
+ continue;
for (var p in arg) {
if (hasProperty(arg, p)) {
- t[p] = arg[p]; // TODO: GH#23368
+ t[p] = arg[p];
}
}
}
@@ -1346,6 +1433,9 @@
/** Do nothing and return true */
function returnTrue() { return true; }
ts.returnTrue = returnTrue;
+ /** Do nothing and return undefined */
+ function returnUndefined() { return undefined; }
+ ts.returnUndefined = returnUndefined;
/** Returns its argument. */
function identity(x) { return x; }
ts.identity = identity;
@@ -1492,7 +1582,7 @@
Debug.assertEachDefined = assertEachDefined;
function assertNever(member, message, stackCrawlMark) {
if (message === void 0) { message = "Illegal value:"; }
- var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member);
+ var detail = typeof member === "object" && "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member);
return fail(message + " " + detail, stackCrawlMark || assertNever);
}
Debug.assertNever = assertNever;
@@ -2795,47 +2885,53 @@
SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment";
// Enum
SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember";
+ // Unparsed
+ SyntaxKind[SyntaxKind["UnparsedPrologue"] = 279] = "UnparsedPrologue";
+ SyntaxKind[SyntaxKind["UnparsedPrepend"] = 280] = "UnparsedPrepend";
+ SyntaxKind[SyntaxKind["UnparsedText"] = 281] = "UnparsedText";
+ SyntaxKind[SyntaxKind["UnparsedInternalText"] = 282] = "UnparsedInternalText";
+ SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 283] = "UnparsedSyntheticReference";
// Top-level nodes
- SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile";
- SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle";
- SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource";
- SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles";
+ SyntaxKind[SyntaxKind["SourceFile"] = 284] = "SourceFile";
+ SyntaxKind[SyntaxKind["Bundle"] = 285] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 286] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 287] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 288] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 289] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature";
- SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag";
- SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 290] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 291] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 292] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 293] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 294] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 295] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 296] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 297] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocSignature"] = 298] = "JSDocSignature";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 299] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 300] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 301] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 302] = "JSDocCallbackTag";
+ SyntaxKind[SyntaxKind["JSDocEnumTag"] = 303] = "JSDocEnumTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 304] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 305] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocThisTag"] = 306] = "JSDocThisTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 307] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 308] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 309] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 310] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 311] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 312] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 313] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 314] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 315] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 316] = "EndOfDeclarationMarker";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 312] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 317] = "Count";
// Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment";
@@ -2862,10 +2958,10 @@
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator";
SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 288] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 310] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 299] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 310] = "LastJSDocTagNode";
/* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword";
/* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
@@ -2972,21 +3068,27 @@
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
})(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
- /* @internal */
var TokenFlags;
(function (TokenFlags) {
TokenFlags[TokenFlags["None"] = 0] = "None";
+ /* @internal */
TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
+ /* @internal */
TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
+ /* @internal */
TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
+ /* @internal */
TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
+ /* @internal */
TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
+ /* @internal */
TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
+ /* @internal */
TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
})(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
var FlowFlags;
@@ -3346,12 +3448,6 @@
TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
/* @internal */
- TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType";
- /* @internal */
- TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral";
- /* @internal */
- TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType";
- /* @internal */
TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
/* @internal */
TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
@@ -3383,28 +3479,29 @@
TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive";
TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable";
TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable";
+ /* @internal */
+ TypeFlags[TypeFlags["ObjectFlagsType"] = 3899392] = "ObjectFlagsType";
// 'Narrowable' types are types where narrowing actually narrows.
// This *should* be every type other than null, undefined, void, and never
TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable";
TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit";
/* @internal */
TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion";
+ // The following flags are aggregated during union and intersection type construction
/* @internal */
- TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening";
- /* @internal */
- TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags";
+ TypeFlags[TypeFlags["IncludesMask"] = 1835007] = "IncludesMask";
// The following flags are used for different purposes during union and intersection type construction
/* @internal */
- TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType";
+ TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
/* @internal */
- TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard";
+ TypeFlags[TypeFlags["IncludesNonWideningType"] = 2097152] = "IncludesNonWideningType";
/* @internal */
- TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject";
+ TypeFlags[TypeFlags["IncludesWildcard"] = 4194304] = "IncludesWildcard";
/* @internal */
- TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags";
+ TypeFlags[TypeFlags["IncludesEmptyObject"] = 8388608] = "IncludesEmptyObject";
// The following flag is used for different purposes by maybeTypeOfKind
/* @internal */
- TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType";
+ TypeFlags[TypeFlags["GenericMappedType"] = 131072] = "GenericMappedType";
})(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
var ObjectFlags;
(function (ObjectFlags) {
@@ -3424,7 +3521,19 @@
ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
+ /* @internal */
+ ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion";
+ /* @internal */
+ ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType";
+ /* @internal */
+ ObjectFlags[ObjectFlags["ContainsObjectLiteral"] = 262144] = "ContainsObjectLiteral";
+ /* @internal */
+ ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType";
ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
+ /* @internal */
+ ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening";
+ /* @internal */
+ ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags";
})(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
/* @internal */
var Variance;
@@ -3469,6 +3578,7 @@
InferenceFlags[InferenceFlags["None"] = 0] = "None";
InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
+ InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
})(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
/**
* Ternary values are defined such that
@@ -3576,9 +3686,10 @@
ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
- ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext";
+ ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
+ ScriptTarget[ScriptTarget["ESNext"] = 7] = "ESNext";
ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
- ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest";
+ ScriptTarget[ScriptTarget["Latest"] = 7] = "Latest";
})(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
var LanguageVariant;
(function (LanguageVariant) {
@@ -3727,6 +3838,7 @@
Extension["Js"] = ".js";
Extension["Jsx"] = ".jsx";
Extension["Json"] = ".json";
+ Extension["TsBuildInfo"] = ".tsbuildinfo";
})(Extension = ts.Extension || (ts.Extension = {}));
/* @internal */
var TransformFlags;
@@ -3734,71 +3846,69 @@
TransformFlags[TransformFlags["None"] = 0] = "None";
// Facts
// - Flags used to indicate that a node or subtree contains syntax that requires transformation.
- TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript";
- TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript";
- TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx";
- TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext";
- TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017";
- TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016";
- TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015";
+ TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
+ TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
+ TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
+ TransformFlags[TransformFlags["ContainsES2019"] = 8] = "ContainsES2019";
+ TransformFlags[TransformFlags["ContainsES2018"] = 16] = "ContainsES2018";
+ TransformFlags[TransformFlags["ContainsES2017"] = 32] = "ContainsES2017";
+ TransformFlags[TransformFlags["ContainsES2016"] = 64] = "ContainsES2016";
TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015";
- TransformFlags[TransformFlags["Generator"] = 256] = "Generator";
- TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
- TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment";
- TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment";
+ TransformFlags[TransformFlags["ContainsGenerator"] = 256] = "ContainsGenerator";
+ TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 512] = "ContainsDestructuringAssignment";
// Markers
// - Flags used to indicate that a subtree contains a specific transformation.
- TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax";
- TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis";
- TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis";
- TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName";
- TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments";
- TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread";
- TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread";
- TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName";
- TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding";
- TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern";
- TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield";
- TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion";
- TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport";
- TransformFlags[TransformFlags["Super"] = 33554432] = "Super";
- TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper";
+ TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 1024] = "ContainsTypeScriptClassSyntax";
+ TransformFlags[TransformFlags["ContainsLexicalThis"] = 2048] = "ContainsLexicalThis";
+ TransformFlags[TransformFlags["ContainsRestOrSpread"] = 4096] = "ContainsRestOrSpread";
+ TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 8192] = "ContainsObjectRestOrSpread";
+ TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 16384] = "ContainsComputedPropertyName";
+ TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 32768] = "ContainsBlockScopedBinding";
+ TransformFlags[TransformFlags["ContainsBindingPattern"] = 65536] = "ContainsBindingPattern";
+ TransformFlags[TransformFlags["ContainsYield"] = 131072] = "ContainsYield";
+ TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 262144] = "ContainsHoistedDeclarationOrCompletion";
+ TransformFlags[TransformFlags["ContainsDynamicImport"] = 524288] = "ContainsDynamicImport";
// Please leave this as 1 << 29.
// It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
// It is a good reminder of how much room we have left
TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
// Assertions
// - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
- TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript";
- TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx";
- TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext";
- TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017";
- TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016";
- TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015";
- TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator";
- TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment";
+ TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
+ TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
+ TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
+ TransformFlags[TransformFlags["AssertES2019"] = 8] = "AssertES2019";
+ TransformFlags[TransformFlags["AssertES2018"] = 16] = "AssertES2018";
+ TransformFlags[TransformFlags["AssertES2017"] = 32] = "AssertES2017";
+ TransformFlags[TransformFlags["AssertES2016"] = 64] = "AssertES2016";
+ TransformFlags[TransformFlags["AssertES2015"] = 128] = "AssertES2015";
+ TransformFlags[TransformFlags["AssertGenerator"] = 256] = "AssertGenerator";
+ TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 512] = "AssertDestructuringAssignment";
// Scope Exclusions
// - Bitmasks that exclude flags from propagating out of a specific context
// into the subtree flags of their container.
- TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes";
- TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes";
- TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes";
- TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes";
- TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes";
- TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes";
- TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes";
- TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes";
- TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes";
- TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes";
- TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes";
- TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes";
- TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes";
- TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes";
- TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes";
- TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes";
+ TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
+ TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
+ TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
+ TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 537371648] = "ArrowFunctionExcludes";
+ TransformFlags[TransformFlags["FunctionExcludes"] = 537373696] = "FunctionExcludes";
+ TransformFlags[TransformFlags["ConstructorExcludes"] = 537372672] = "ConstructorExcludes";
+ TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 537372672] = "MethodOrAccessorExcludes";
+ TransformFlags[TransformFlags["PropertyExcludes"] = 536872960] = "PropertyExcludes";
+ TransformFlags[TransformFlags["ClassExcludes"] = 536888320] = "ClassExcludes";
+ TransformFlags[TransformFlags["ModuleExcludes"] = 537168896] = "ModuleExcludes";
+ TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
+ TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536896512] = "ObjectLiteralExcludes";
+ TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536875008] = "ArrayLiteralOrCallOrNewExcludes";
+ TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 536944640] = "VariableDeclarationListExcludes";
+ TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
+ TransformFlags[TransformFlags["CatchClauseExcludes"] = 536879104] = "CatchClauseExcludes";
+ TransformFlags[TransformFlags["BindingPatternExcludes"] = 536875008] = "BindingPatternExcludes";
+ // Propagating flags
+ // - Bitmasks for flags that should propagate from a child
+ TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 2048] = "PropertyNamePropagatingFlags";
// Masks
// - Additional bitmasks
- TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask";
})(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
var EmitFlags;
(function (EmitFlags) {
@@ -3880,6 +3990,20 @@
EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
})(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
+ /*@internal*/
+ var BundleFileSectionKind;
+ (function (BundleFileSectionKind) {
+ BundleFileSectionKind["Prologue"] = "prologue";
+ BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
+ BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
+ BundleFileSectionKind["Reference"] = "reference";
+ BundleFileSectionKind["Type"] = "type";
+ BundleFileSectionKind["Lib"] = "lib";
+ BundleFileSectionKind["Prepend"] = "prepend";
+ BundleFileSectionKind["Text"] = "text";
+ BundleFileSectionKind["Internal"] = "internal";
+ // comments?
+ })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
var ListFormat;
(function (ListFormat) {
ListFormat[ListFormat["None"] = 0] = "None";
@@ -4026,8 +4150,11 @@
*/
/* @internal */
function generateDjb2Hash(data) {
- var chars = data.split("").map(function (str) { return str.charCodeAt(0); });
- return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381);
+ var acc = 5381;
+ for (var i = 0; i < data.length; i++) {
+ acc = ((acc << 5) + acc) + data.charCodeAt(i);
+ }
+ return acc.toString();
}
ts.generateDjb2Hash = generateDjb2Hash;
/**
@@ -4287,6 +4414,8 @@
: FileWatcherEventKind.Changed;
}
ts.getFileWatcherEventKind = getFileWatcherEventKind;
+ /*@internal*/
+ ts.ignoredPaths = ["/node_modules/.", "/.git"];
/**
* 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
@@ -4311,6 +4440,8 @@
else {
directoryWatcher = {
watcher: host.watchDirectory(dirName, function (fileName) {
+ if (isIgnoredPath(fileName))
+ return;
// Call the actual callback
callbackCache.forEach(function (callbacks, rootDirName) {
if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
@@ -4360,7 +4491,7 @@
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 filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
+ return !isIgnoredPath(childFullName) && 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;
/**
@@ -4377,6 +4508,16 @@
(newChildWatches || (newChildWatches = [])).push(childWatcher);
}
}
+ function isIgnoredPath(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
+ }
+ function isInPath(path, searchPath) {
+ if (ts.stringContains(path, searchPath))
+ return true;
+ if (host.useCaseSensitiveFileNames)
+ return false;
+ return ts.stringContains(toCanonicalFilePath(path), searchPath);
+ }
}
ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher;
function getNodeMajorVersion() {
@@ -4445,8 +4586,18 @@
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!nodeSystem.directoryExists(directoryName)) {
+ // Wrapped in a try-catch to prevent crashing if we are in a race
+ // with another copy of ourselves to create the same directory
+ try {
_fs.mkdirSync(directoryName);
}
+ catch (e) {
+ if (e.code !== "EEXIST") {
+ // Failed for some other reason (access denied?); still throw
+ throw e;
+ }
+ }
+ }
},
getExecutingFilePath: function () {
return __filename;
@@ -4462,7 +4613,7 @@
getModifiedTime: getModifiedTime,
setModifiedTime: setModifiedTime,
deleteFile: deleteFile,
- createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash,
+ createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
createSHA256Hash: _crypto ? createSHA256Hash : undefined,
getMemoryUsage: function () {
if (global.gc) {
@@ -4850,7 +5001,7 @@
}
}
function readDirectory(path, extensions, excludes, includes, depth) {
- return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries);
+ return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
}
function fileSystemEntryExists(path, entryKind) {
try {
@@ -4906,11 +5057,6 @@
return;
}
}
- function createMD5HashUsingNativeCrypto(data) {
- var hash = _crypto.createHash("md5");
- hash.update(data);
- return hash.digest("hex");
- }
function createSHA256Hash(data) {
var hash = _crypto.createHash("sha256");
hash.update(data);
@@ -5171,7 +5317,6 @@
Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."),
Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."),
- Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."),
Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."),
A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."),
Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."),
@@ -5262,6 +5407,8 @@
An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."),
A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."),
A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."),
+ readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types: diag(1354, ts.DiagnosticCategory.Error, "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354", "'readonly' type modifier is only permitted on array and tuple literal types."),
+ A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal: diag(1355, ts.DiagnosticCategory.Error, "A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal_1355", "A 'const' assertion can only be applied to a string, number, boolean, array, or object literal."),
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."),
@@ -5356,7 +5503,7 @@
Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."),
Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
- Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."),
+ This_overload_signature_is_not_compatible_with_its_implementation_signature: diag(2394, ts.DiagnosticCategory.Error, "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394", "This overload signature is not compatible with its implementation signature."),
Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."),
Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."),
Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."),
@@ -5529,15 +5676,20 @@
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."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."),
Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."),
_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
+ Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."),
+ Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
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."),
@@ -5644,6 +5796,12 @@
This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."),
This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."),
_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."),
+ Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided: diag(2748, ts.DiagnosticCategory.Error, "Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided_2748", "Cannot access ambient const enums when the '--isolatedModules' flag is provided."),
+ _0_refers_to_a_value_but_is_being_used_as_a_type_here: diag(2749, ts.DiagnosticCategory.Error, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_2749", "'{0}' refers to a value, but is being used as a type here."),
+ The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
+ Circularity_originates_in_type_at_this_location: diag(2751, ts.DiagnosticCategory.Error, "Circularity_originates_in_type_at_this_location_2751", "Circularity originates in type at this location."),
+ The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
+ Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
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}'."),
@@ -5727,6 +5885,7 @@
Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
@@ -5775,7 +5934,7 @@
Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."),
Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
- Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."),
+ Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'."),
Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."),
Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
@@ -5994,6 +6153,16 @@
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."),
Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
+ Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
+ Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
+ A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
+ A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
+ Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
+ Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
+ Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
+ Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
+ Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
+ Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
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."),
The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
@@ -6030,7 +6199,7 @@
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'."),
+ The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."),
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."),
Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
@@ -6210,6 +6379,7 @@
Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
+ Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
};
})(ts || (ts = {}));
var ts;
@@ -6697,16 +6867,20 @@
return pos;
}
var shebangTriviaRegex = /^#!.*/;
+ /*@internal*/
function isShebangTrivia(text, pos) {
// Shebangs check must only be done at the start of the file
ts.Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
+ ts.isShebangTrivia = isShebangTrivia;
+ /*@internal*/
function scanShebangTrivia(text, pos) {
var shebang = shebangTriviaRegex.exec(text)[0];
pos = pos + shebang.length;
return pos;
}
+ ts.scanShebangTrivia = scanShebangTrivia;
/**
* Invokes a callback for each comment range following the provided position.
*
@@ -6733,8 +6907,15 @@
var pendingKind;
var pendingHasTrailingNewLine;
var hasPendingCommentRange = false;
- var collecting = trailing || pos === 0;
+ var collecting = trailing;
var accumulator = initial;
+ if (pos === 0) {
+ collecting = true;
+ var shebang = getShebang(text);
+ if (shebang) {
+ pos = shebang.length;
+ }
+ }
scan: while (pos >= 0 && pos < text.length) {
var ch = text.charCodeAt(pos);
switch (ch) {
@@ -7969,6 +8150,7 @@
}
pos++;
}
+ tokenValue = text.substring(startPos, pos);
return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
}
// Scans a JSX identifier; these differ from normal identifiers in that
@@ -8050,8 +8232,8 @@
pos++;
return token = 14 /* NoSubstitutionTemplateLiteral */;
}
- if (isIdentifierStart(ch, 6 /* Latest */)) {
- while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) {
+ if (isIdentifierStart(ch, 7 /* Latest */)) {
+ while (isIdentifierPart(text.charCodeAt(pos), 7 /* Latest */) && pos < end) {
pos++;
}
tokenValue = text.substring(tokenPos, pos);
@@ -8409,7 +8591,7 @@
}
}
function getSourceFileOfNode(node) {
- while (node && node.kind !== 279 /* SourceFile */) {
+ while (node && node.kind !== 284 /* SourceFile */) {
node = node.parent;
}
return node;
@@ -8496,10 +8678,7 @@
return !nodeIsMissing(node);
}
ts.nodeIsPresent = nodeIsPresent;
- /**
- * Prepends statements to an array while taking care of prologue directives.
- */
- function addStatementsAfterPrologue(to, from) {
+ function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
if (from === undefined || from.length === 0)
return to;
var statementIndex = 0;
@@ -8512,7 +8691,44 @@
to.splice.apply(to, [statementIndex, 0].concat(from));
return to;
}
- ts.addStatementsAfterPrologue = addStatementsAfterPrologue;
+ function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
+ if (statement === undefined)
+ return to;
+ 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(statementIndex, 0, statement);
+ return to;
+ }
+ function isAnyPrologueDirective(node) {
+ return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
+ }
+ /**
+ * Prepends statements to an array while taking care of prologue directives.
+ */
+ function insertStatementsAfterStandardPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isPrologueDirective);
+ }
+ ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
+ function insertStatementsAfterCustomPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
+ }
+ ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
+ /**
+ * Prepends statements to an array while taking care of prologue directives.
+ */
+ function insertStatementAfterStandardPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isPrologueDirective);
+ }
+ ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
+ function insertStatementAfterCustomPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
+ }
+ ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
/**
* Determine if the given comment is a triple-slash
*
@@ -8555,7 +8771,7 @@
// 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 === 306 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 311 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -8574,7 +8790,7 @@
}
ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
function isJSDocTypeExpressionOrChild(node) {
- return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
+ return node.kind === 288 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
}
function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
@@ -8701,7 +8917,7 @@
return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body);
}
function isBlockScopedContainerTopLevel(node) {
- return node.kind === 279 /* SourceFile */ ||
+ return node.kind === 284 /* SourceFile */ ||
node.kind === 244 /* ModuleDeclaration */ ||
ts.isFunctionLike(node);
}
@@ -8719,7 +8935,7 @@
// - 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 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node.parent);
case 245 /* ModuleBlock */:
return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
@@ -8737,7 +8953,7 @@
ts.isEffectiveExternalModule = isEffectiveExternalModule;
function isBlockScope(node, parentNode) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 274 /* CatchClause */:
case 244 /* ModuleDeclaration */:
@@ -8762,9 +8978,9 @@
ts.isBlockScope = isBlockScope;
function isDeclarationWithTypeParameters(node) {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
- case 293 /* JSDocSignature */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 298 /* JSDocSignature */:
return true;
default:
ts.assertType(node);
@@ -8780,12 +8996,12 @@
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
@@ -8930,7 +9146,7 @@
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* 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
@@ -9105,7 +9321,7 @@
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case 150 /* TypeParameter */:
return node === parent.constraint;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return node === parent.constraint;
case 154 /* PropertyDeclaration */:
case 153 /* PropertySignature */:
@@ -9365,7 +9581,7 @@
}
ts.getContainingClass = getContainingClass;
function getThisContainer(node, includeArrowFunctions) {
- ts.Debug.assert(node.kind !== 279 /* SourceFile */);
+ ts.Debug.assert(node.kind !== 284 /* SourceFile */);
while (true) {
node = node.parent;
if (!node) {
@@ -9419,7 +9635,7 @@
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 243 /* EnumDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return node;
}
}
@@ -9502,6 +9718,11 @@
}
}
ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
+ function isSuperOrSuperProperty(node) {
+ return node.kind === 98 /* SuperKeyword */
+ || isSuperProperty(node);
+ }
+ ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
/**
* Determines whether a node is a property or element access expression for `super`.
*/
@@ -10127,7 +10348,7 @@
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
function isJSDocTypeAlias(node) {
- return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 309 /* JSDocTypedefTag */ || node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocTypeAlias = isJSDocTypeAlias;
function isTypeAlias(node) {
@@ -10271,7 +10492,7 @@
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 === 290 /* JSDocVariadicType */;
+ return node.dotDotDotToken !== undefined || !!type && type.kind === 295 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -10509,14 +10730,15 @@
}
ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
function getEffectiveBaseTypeNode(node) {
- if (isInJSFile(node)) {
+ var baseType = getClassExtendsHeritageElement(node);
+ if (baseType && isInJSFile(node)) {
// Prefer an @augments tag because it may have type parameters.
var tag = ts.getJSDocAugmentsTag(node);
if (tag) {
return tag.class;
}
}
- return getClassExtendsHeritageElement(node);
+ return baseType;
}
ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
function getClassExtendsHeritageElement(node) {
@@ -10755,7 +10977,7 @@
|| kind === 158 /* GetAccessor */
|| kind === 159 /* SetAccessor */
|| kind === 244 /* ModuleDeclaration */
- || kind === 279 /* SourceFile */;
+ || kind === 284 /* SourceFile */;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(range) {
@@ -10832,7 +11054,7 @@
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return 0;
case 208 /* SpreadElement */:
return 1;
@@ -11150,6 +11372,9 @@
lineStart = true;
}
}
+ function getTextPosWithWriteLine() {
+ return lineStart ? output.length : (output.length + newLine.length);
+ }
reset();
return {
write: write,
@@ -11178,7 +11403,8 @@
writeStringLiteral: write,
writeSymbol: function (s, _) { return write(s); },
writeTrailingSemicolon: write,
- writeComment: write
+ writeComment: write,
+ getTextPosWithWriteLine: getTextPosWithWriteLine
};
}
ts.createTextWriter = createTextWriter;
@@ -11307,23 +11533,27 @@
function getSourceFilesToEmit(host, targetSourceFile) {
var options = host.getCompilerOptions();
var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); };
+ var getResolvedProjectReferenceToRedirect = function (fileName) { return host.getResolvedProjectReferenceToRedirect(fileName); };
if (options.outFile || options.out) {
var moduleKind = ts.getEmitModuleKind(options);
var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
// Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
return ts.filter(host.getSourceFiles(), function (sourceFile) {
- return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary);
+ return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect);
});
}
else {
var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
- return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); });
+ return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
}
}
ts.getSourceFilesToEmit = getSourceFilesToEmit;
/** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
- function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) {
- return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile);
+ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect) {
+ return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
+ !sourceFile.isDeclarationFile &&
+ !isSourceFileFromExternalLibrary(sourceFile) &&
+ !(isJsonSourceFile(sourceFile) && getResolvedProjectReferenceToRedirect(sourceFile.fileName));
}
ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
function getSourceFilePathInNewDir(fileName, host, newDirPath) {
@@ -11469,7 +11699,7 @@
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 === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 296 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
}
/**
* Gets the effective type annotation of the value parameter of a set accessor. If the node
@@ -12374,7 +12604,7 @@
}
ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
function getObjectFlags(type) {
- return type.flags & 524288 /* Object */ ? type.objectFlags : 0;
+ return type.flags & 3899392 /* ObjectFlagsType */ ? type.objectFlags : 0;
}
ts.getObjectFlags = getObjectFlags;
function typeHasCallOrConstructSignatures(type, checker) {
@@ -12441,25 +12671,37 @@
|| kind === 96 /* NullKeyword */
|| kind === 132 /* NeverKeyword */
|| kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
+ || kind === 289 /* JSDocAllType */
+ || kind === 290 /* JSDocUnknownType */
+ || kind === 291 /* JSDocNullableType */
+ || kind === 292 /* JSDocNonNullableType */
+ || kind === 293 /* JSDocOptionalType */
+ || kind === 294 /* JSDocFunctionType */
+ || kind === 295 /* JSDocVariadicType */;
}
ts.isTypeNodeKind = isTypeNodeKind;
function isAccessExpression(node) {
return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */;
}
ts.isAccessExpression = isAccessExpression;
+ function isBundleFileTextLike(section) {
+ switch (section.kind) {
+ case "text" /* Text */:
+ case "internal" /* Internal */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isBundleFileTextLike = isBundleFileTextLike;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
switch (options.target) {
- case 6 /* ESNext */:
+ case 7 /* ESNext */:
return "lib.esnext.full.d.ts";
+ case 6 /* ES2019 */:
+ return "lib.es2019.full.d.ts";
case 5 /* ES2018 */:
return "lib.es2018.full.d.ts";
case 4 /* ES2017 */:
@@ -12913,8 +13155,8 @@
switch (declaration.kind) {
case 72 /* Identifier */:
return declaration;
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */: {
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */: {
var name = declaration.name;
if (name.kind === 148 /* QualifiedName */) {
return name.right;
@@ -12938,7 +13180,7 @@
return undefined;
}
}
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
case 254 /* ExportAssignment */: {
var expression = declaration.expression;
@@ -13142,7 +13384,7 @@
return ts.emptyArray;
}
if (ts.isJSDocTypeAlias(node)) {
- ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */);
+ ts.Debug.assert(node.parent.kind === 296 /* JSDocComment */);
return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
}
if (node.typeParameters) {
@@ -13404,12 +13646,17 @@
return node.kind === 194 /* TypeAssertionExpression */;
}
ts.isTypeAssertion = isTypeAssertion;
+ function isConstTypeReference(node) {
+ return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
+ node.typeName.escapedText === "const" && !node.typeArguments;
+ }
+ ts.isConstTypeReference = isConstTypeReference;
function isParenthesizedExpression(node) {
return node.kind === 195 /* ParenthesizedExpression */;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 308 /* PartiallyEmittedExpression */) {
+ while (node.kind === 313 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13756,108 +14003,128 @@
ts.isEnumMember = isEnumMember;
// Top-level nodes
function isSourceFile(node) {
- return node.kind === 279 /* SourceFile */;
+ return node.kind === 284 /* SourceFile */;
}
ts.isSourceFile = isSourceFile;
function isBundle(node) {
- return node.kind === 280 /* Bundle */;
+ return node.kind === 285 /* Bundle */;
}
ts.isBundle = isBundle;
function isUnparsedSource(node) {
- return node.kind === 281 /* UnparsedSource */;
+ return node.kind === 286 /* UnparsedSource */;
}
ts.isUnparsedSource = isUnparsedSource;
+ function isUnparsedPrepend(node) {
+ return node.kind === 280 /* UnparsedPrepend */;
+ }
+ ts.isUnparsedPrepend = isUnparsedPrepend;
+ function isUnparsedTextLike(node) {
+ switch (node.kind) {
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isUnparsedTextLike = isUnparsedTextLike;
+ function isUnparsedNode(node) {
+ return isUnparsedTextLike(node) ||
+ node.kind === 279 /* UnparsedPrologue */ ||
+ node.kind === 283 /* UnparsedSyntheticReference */;
+ }
+ ts.isUnparsedNode = isUnparsedNode;
// JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 283 /* JSDocTypeExpression */;
+ return node.kind === 288 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 284 /* JSDocAllType */;
+ return node.kind === 289 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 285 /* JSDocUnknownType */;
+ return node.kind === 290 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 286 /* JSDocNullableType */;
+ return node.kind === 291 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 287 /* JSDocNonNullableType */;
+ return node.kind === 292 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 288 /* JSDocOptionalType */;
+ return node.kind === 293 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 289 /* JSDocFunctionType */;
+ return node.kind === 294 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 290 /* JSDocVariadicType */;
+ return node.kind === 295 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 291 /* JSDocComment */;
+ return node.kind === 296 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 295 /* JSDocAugmentsTag */;
+ return node.kind === 300 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 296 /* JSDocClassTag */;
+ return node.kind === 301 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocEnumTag(node) {
- return node.kind === 298 /* JSDocEnumTag */;
+ return node.kind === 303 /* JSDocEnumTag */;
}
ts.isJSDocEnumTag = isJSDocEnumTag;
function isJSDocThisTag(node) {
- return node.kind === 301 /* JSDocThisTag */;
+ return node.kind === 306 /* JSDocThisTag */;
}
ts.isJSDocThisTag = isJSDocThisTag;
function isJSDocParameterTag(node) {
- return node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 300 /* JSDocReturnTag */;
+ return node.kind === 305 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 302 /* JSDocTypeTag */;
+ return node.kind === 307 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 303 /* JSDocTemplateTag */;
+ return node.kind === 308 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 304 /* JSDocTypedefTag */;
+ return node.kind === 309 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */;
+ return node.kind === 310 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 310 /* JSDocPropertyTag */ || node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 292 /* JSDocTypeLiteral */;
+ return node.kind === 297 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
function isJSDocCallbackTag(node) {
- return node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocCallbackTag = isJSDocCallbackTag;
function isJSDocSignature(node) {
- return node.kind === 293 /* JSDocSignature */;
+ return node.kind === 298 /* JSDocSignature */;
}
ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
@@ -13868,7 +14135,7 @@
(function (ts) {
/* @internal */
function isSyntaxList(n) {
- return n.kind === 306 /* SyntaxList */;
+ return n.kind === 311 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
/* @internal */
@@ -14020,11 +14287,11 @@
switch (kind) {
case 155 /* MethodSignature */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 166 /* ConstructorType */:
return true;
default:
@@ -14315,8 +14582,8 @@
case 208 /* SpreadElement */:
case 212 /* AsExpression */:
case 210 /* OmittedExpression */:
- case 309 /* CommaListExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 314 /* CommaListExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -14330,12 +14597,12 @@
ts.isAssertionExpression = isAssertionExpression;
/* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 308 /* PartiallyEmittedExpression */;
+ return node.kind === 313 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
/* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 307 /* NotEmittedStatement */;
+ return node.kind === 312 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
@@ -14446,9 +14713,9 @@
|| kind === 242 /* TypeAliasDeclaration */
|| kind === 150 /* TypeParameter */
|| kind === 237 /* VariableDeclaration */
- || kind === 304 /* JSDocTypedefTag */
- || kind === 297 /* JSDocCallbackTag */
- || kind === 305 /* JSDocPropertyTag */;
+ || kind === 309 /* JSDocTypedefTag */
+ || kind === 302 /* JSDocCallbackTag */
+ || kind === 310 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
return kind === 239 /* FunctionDeclaration */
@@ -14483,14 +14750,14 @@
|| kind === 219 /* VariableStatement */
|| kind === 224 /* WhileStatement */
|| kind === 231 /* WithStatement */
- || kind === 307 /* NotEmittedStatement */
- || kind === 311 /* EndOfDeclarationMarker */
- || kind === 310 /* MergeDeclarationMarker */;
+ || kind === 312 /* NotEmittedStatement */
+ || kind === 316 /* EndOfDeclarationMarker */
+ || kind === 315 /* MergeDeclarationMarker */;
}
/* @internal */
function isDeclaration(node) {
if (node.kind === 150 /* TypeParameter */) {
- return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node);
+ return (node.parent && node.parent.kind !== 308 /* JSDocTemplateTag */) || ts.isInJSFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -14585,18 +14852,18 @@
/** True if node is of some JSDoc syntax kind. */
/* @internal */
function isJSDocNode(node) {
- return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */;
+ return node.kind >= 288 /* FirstJSDocNode */ && node.kind <= 310 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
+ return node.kind === 296 /* 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 >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */;
+ return node.kind >= 299 /* FirstJSDocTagNode */ && node.kind <= 310 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -14913,6 +15180,10 @@
return !!(compilerOptions.declaration || compilerOptions.composite);
}
ts.getEmitDeclarations = getEmitDeclarations;
+ function isIncrementalCompilation(options) {
+ return !!(options.incremental || options.composite);
+ }
+ ts.isIncrementalCompilation = isIncrementalCompilation;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
}
@@ -15600,7 +15871,7 @@
}
ts.getRegexFromPattern = getRegexFromPattern;
/** @param path directory of the tsconfig.json */
- function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) {
+ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
path = ts.normalizePath(path);
currentDirectory = ts.normalizePath(currentDirectory);
var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
@@ -15610,12 +15881,18 @@
// Associate an array of results with each include regex. This keeps results in order of the "include" order.
// If there are no "includes", then just put everything in results[0].
var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
+ var visited = ts.createMap();
+ var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
var basePath = _a[_i];
visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
}
return ts.flatten(results);
function visitDirectory(path, absolutePath, depth) {
+ var canonicalPath = toCanonical(realpath(absolutePath));
+ if (visited.has(canonicalPath))
+ return;
+ visited.set(canonicalPath, true);
var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
var _loop_1 = function (current) {
var name = combinePaths(path, current);
@@ -15998,6 +16275,19 @@
return arr.slice(index);
}
ts.sliceAfter = sliceAfter;
+ function addRelatedInfo(diagnostic) {
+ var _a;
+ var relatedInformation = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ relatedInformation[_i - 1] = arguments[_i];
+ }
+ if (!diagnostic.relatedInformation) {
+ diagnostic.relatedInformation = [];
+ }
+ (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
+ return diagnostic;
+ }
+ ts.addRelatedInfo = addRelatedInfo;
function minAndMax(arr, getValue) {
Debug.assert(arr.length !== 0);
var min = getValue(arr[0]);
@@ -16197,7 +16487,7 @@
var SourceFileConstructor;
// tslint:enable variable-name
function createNode(kind, pos, end) {
- if (kind === 279 /* SourceFile */) {
+ if (kind === 284 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 72 /* Identifier */) {
@@ -16448,7 +16738,7 @@
case 218 /* Block */:
case 245 /* ModuleBlock */:
return visitNodes(cbNode, cbNodes, node.statements);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return visitNodes(cbNode, cbNodes, node.statements) ||
visitNode(cbNode, node.endOfFileToken);
case 219 /* VariableStatement */:
@@ -16597,7 +16887,7 @@
return visitNode(cbNode, node.expression);
case 258 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
case 260 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
@@ -16626,60 +16916,60 @@
return visitNode(cbNode, node.tagName);
case 171 /* OptionalType */:
case 172 /* RestType */:
- case 283 /* JSDocTypeExpression */:
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 288 /* JSDocOptionalType */:
- case 290 /* JSDocVariadicType */:
+ case 288 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 293 /* JSDocOptionalType */:
+ case 295 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return visitNode(cbNode, node.tagName) ||
(node.isNameFirst
? visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression)
: visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name));
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.constraint) ||
visitNodes(cbNode, cbNodes, node.typeParameters);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return visitNode(cbNode, node.tagName) ||
(node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ node.typeExpression.kind === 288 /* JSDocTypeExpression */
? visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName)
: visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression));
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.typeExpression);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return ts.forEach(node.jsDocPropertyTags, cbNode);
- case 294 /* JSDocTag */:
- case 296 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
return visitNode(cbNode, node.tagName);
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -16759,7 +17049,7 @@
(function (Parser) {
// Share a single scanner across all calls to parse a source file. This helps speed things
// up by avoiding the cost of creating/compiling scanners over and over again.
- var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true);
+ var scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ true);
var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */;
// capture constructors in 'initializeState' to avoid null checks
// tslint:disable variable-name
@@ -17053,7 +17343,7 @@
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(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
+ var sourceFile = new SourceFileConstructor(284 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
@@ -18253,9 +18543,9 @@
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(284 /* JSDocAllType */);
+ var result = createNode(289 /* JSDocAllType */);
if (postFixEquals) {
- return createPostfixType(288 /* JSDocOptionalType */, result);
+ return createPostfixType(293 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -18263,7 +18553,7 @@
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(287 /* JSDocNonNullableType */);
+ var result = createNode(292 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -18287,18 +18577,18 @@
token() === 30 /* GreaterThanToken */ ||
token() === 59 /* EqualsToken */ ||
token() === 50 /* BarToken */) {
- var result = createNode(285 /* JSDocUnknownType */, pos);
+ var result = createNode(290 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(286 /* JSDocNullableType */, pos);
+ var result = createNode(291 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(289 /* JSDocFunctionType */);
+ var result = createNodeWithJSDoc(294 /* JSDocFunctionType */);
nextToken();
fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
@@ -18322,12 +18612,12 @@
var type = parseTypeOrTypePredicate();
scanner.setInJSDocType(false);
if (dotdotdot) {
- var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos);
+ var variadic = createNode(295 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 59 /* EqualsToken */) {
- return createPostfixType(288 /* JSDocOptionalType */, type);
+ return createPostfixType(293 /* JSDocOptionalType */, type);
}
return type;
}
@@ -18699,7 +18989,7 @@
return finishNode(node);
}
var type = parseType();
- if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) {
+ if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 291 /* JSDocNullableType */ && type.pos === type.type.pos) {
type.kind = 171 /* OptionalType */;
}
return type;
@@ -18837,6 +19127,7 @@
case 135 /* NumberKeyword */:
case 146 /* BigIntKeyword */:
case 123 /* BooleanKeyword */:
+ case 133 /* ReadonlyKeyword */:
case 139 /* SymbolKeyword */:
case 142 /* UniqueKeyword */:
case 106 /* VoidKeyword */:
@@ -18885,14 +19176,14 @@
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 52 /* ExclamationToken */:
- type = createPostfixType(287 /* JSDocNonNullableType */, type);
+ type = createPostfixType(292 /* JSDocNonNullableType */, type);
break;
case 56 /* 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 = createPostfixType(286 /* JSDocNullableType */, type);
+ type = createPostfixType(291 /* JSDocNullableType */, type);
break;
case 22 /* OpenBracketToken */:
parseExpected(22 /* OpenBracketToken */);
@@ -18942,6 +19233,7 @@
switch (operator) {
case 129 /* KeyOfKeyword */:
case 142 /* UniqueKeyword */:
+ case 133 /* ReadonlyKeyword */:
return parseTypeOperator(operator);
case 127 /* InferKeyword */:
return parseInferType();
@@ -20001,7 +20293,8 @@
}
function parseJsxText() {
var node = createNode(11 /* JsxText */);
- node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
+ node.text = scanner.getTokenValue();
+ node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
currentToken = scanner.scanJsxToken();
return finishNode(node);
}
@@ -21816,8 +22109,8 @@
var JSDocParser;
(function (JSDocParser) {
function parseJSDocTypeExpressionForTests(content, start, length) {
- initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
- sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
+ initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ sourceFile = createSourceFile("file.js", 7 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
scanner.setText(content, start, length);
currentToken = scanner.scan();
var jsDocTypeExpression = parseJSDocTypeExpression();
@@ -21828,7 +22121,7 @@
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
// Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(283 /* JSDocTypeExpression */);
+ var result = createNode(288 /* JSDocTypeExpression */);
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -21839,7 +22132,7 @@
}
JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
function parseIsolatedJSDocComment(content, start, length) {
- initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion
var jsDoc = parseJSDocCommentWorker(start, length);
var diagnostics = parseDiagnostics;
@@ -21991,7 +22284,7 @@
}
}
function createJSDocComment() {
- var result = createNode(291 /* JSDocComment */, start);
+ var result = createNode(296 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -22158,7 +22451,7 @@
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(start, tagName) {
- var result = createNode(294 /* JSDocTag */, start);
+ var result = createNode(299 /* JSDocTag */, start);
result.tagName = tagName;
return finishNode(result);
}
@@ -22217,8 +22510,8 @@
typeExpression = tryParseTypeExpression();
}
var result = target === 1 /* Property */ ?
- createNode(305 /* JSDocPropertyTag */, start) :
- createNode(299 /* JSDocParameterTag */, start);
+ createNode(310 /* JSDocPropertyTag */, start) :
+ createNode(304 /* JSDocParameterTag */, start);
var comment = parseTagComments(indent + scanner.getStartPos() - start);
var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
if (nestedTypeLiteral) {
@@ -22235,18 +22528,18 @@
}
function parseNestedTypeLiteral(typeExpression, name, target, indent) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(288 /* 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, indent, name); })) {
- if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) {
+ if (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 169 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
@@ -22257,25 +22550,25 @@
}
}
function parseReturnTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 305 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(300 /* JSDocReturnTag */, start);
+ var result = createNode(305 /* JSDocReturnTag */, start);
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 307 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(302 /* JSDocTypeTag */, start);
+ var result = createNode(307 /* JSDocTypeTag */, start);
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(start, tagName) {
- var result = createNode(295 /* JSDocAugmentsTag */, start);
+ var result = createNode(300 /* JSDocAugmentsTag */, start);
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
return finishNode(result);
@@ -22302,19 +22595,19 @@
return node;
}
function parseClassTag(start, tagName) {
- var tag = createNode(296 /* JSDocClassTag */, start);
+ var tag = createNode(301 /* JSDocClassTag */, start);
tag.tagName = tagName;
return finishNode(tag);
}
function parseThisTag(start, tagName) {
- var tag = createNode(301 /* JSDocThisTag */, start);
+ var tag = createNode(306 /* JSDocThisTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
return finishNode(tag);
}
function parseEnumTag(start, tagName) {
- var tag = createNode(298 /* JSDocEnumTag */, start);
+ var tag = createNode(303 /* JSDocEnumTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
@@ -22323,7 +22616,7 @@
function parseTypedefTag(start, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespaceOrAsterisk();
- var typedefTag = createNode(304 /* JSDocTypedefTag */, start);
+ var typedefTag = createNode(309 /* JSDocTypedefTag */, start);
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace();
typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
@@ -22337,9 +22630,9 @@
var childTypeTag = void 0;
while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start);
}
- if (child.kind === 302 /* JSDocTypeTag */) {
+ if (child.kind === 307 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -22385,14 +22678,14 @@
return typeNameOrNamespaceName;
}
function parseCallbackTag(start, tagName, indent) {
- var callbackTag = createNode(297 /* JSDocCallbackTag */, start);
+ var callbackTag = createNode(302 /* JSDocCallbackTag */, start);
callbackTag.tagName = tagName;
callbackTag.fullName = parseJSDocTypeNameWithNamespace();
callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
skipWhitespace();
callbackTag.comment = parseTagComments(indent);
var child;
- var jsdocSignature = createNode(293 /* JSDocSignature */, start);
+ var jsdocSignature = createNode(298 /* JSDocSignature */, start);
jsdocSignature.parameters = [];
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
@@ -22400,7 +22693,7 @@
var returnTag = tryParse(function () {
if (parseOptionalJsdoc(58 /* AtToken */)) {
var tag = parseTag(indent);
- if (tag && tag.kind === 300 /* JSDocReturnTag */) {
+ if (tag && tag.kind === 305 /* JSDocReturnTag */) {
return tag;
}
}
@@ -22445,7 +22738,7 @@
case 58 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target, indent);
- if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) &&
+ if (child && (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) &&
target !== 4 /* CallbackParameter */ &&
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
@@ -22515,7 +22808,7 @@
skipWhitespace();
typeParameters.push(typeParameter);
} while (parseOptionalJsdoc(27 /* CommaToken */));
- var result = createNode(303 /* JSDocTemplateTag */, start);
+ var result = createNode(308 /* JSDocTemplateTag */, start);
result.tagName = tagName;
result.constraint = constraint;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -23293,6 +23586,7 @@
["es2016", "lib.es2016.d.ts"],
["es2017", "lib.es2017.d.ts"],
["es2018", "lib.es2018.d.ts"],
+ ["es2019", "lib.es2019.d.ts"],
["esnext", "lib.esnext.d.ts"],
// Host only
["dom", "lib.dom.d.ts"],
@@ -23316,12 +23610,16 @@
["es2017.string", "lib.es2017.string.d.ts"],
["es2017.intl", "lib.es2017.intl.d.ts"],
["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
+ ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
["es2018.intl", "lib.es2018.intl.d.ts"],
["es2018.promise", "lib.es2018.promise.d.ts"],
["es2018.regexp", "lib.es2018.regexp.d.ts"],
- ["esnext.array", "lib.esnext.array.d.ts"],
- ["esnext.symbol", "lib.esnext.symbol.d.ts"],
- ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"],
+ ["es2019.array", "lib.es2019.array.d.ts"],
+ ["es2019.string", "lib.es2019.string.d.ts"],
+ ["es2019.symbol", "lib.es2019.symbol.d.ts"],
+ ["esnext.array", "lib.es2019.array.d.ts"],
+ ["esnext.symbol", "lib.es2019.symbol.d.ts"],
+ ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
["esnext.intl", "lib.esnext.intl.d.ts"],
["esnext.bigint", "lib.esnext.bigint.d.ts"]
];
@@ -23467,14 +23765,15 @@
es2016: 3 /* ES2016 */,
es2017: 4 /* ES2017 */,
es2018: 5 /* ES2018 */,
- esnext: 6 /* ESNext */,
+ es2019: 6 /* ES2019 */,
+ esnext: 7 /* ESNext */,
}),
affectsSourceFile: true,
affectsModuleResolution: true,
paramType: ts.Diagnostics.VERSION,
showInSimplifiedHelpView: true,
category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT,
+ description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT,
},
{
name: "module",
@@ -23596,6 +23895,22 @@
description: ts.Diagnostics.Enable_project_compilation,
},
{
+ name: "incremental",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_incremental_compilation,
+ },
+ {
+ name: "tsBuildInfoFile",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE,
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
+ },
+ {
name: "removeComments",
type: "boolean",
showInSimplifiedHelpView: true,
@@ -25021,7 +25336,7 @@
}
function directoryOfCombinedPath(fileName, basePath) {
// Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
- // until consistient casing errors are reported
+ // until consistent casing errors are reported
return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
}
/**
@@ -27313,7 +27628,7 @@
return "__constructor" /* Constructor */;
case 165 /* FunctionType */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return "__call" /* Call */;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
@@ -27322,7 +27637,7 @@
return "__index" /* Index */;
case 255 /* ExportDeclaration */:
return "__export" /* ExportStar */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// json file should behave as
// module.exports = ...
return "export=" /* ExportEquals */;
@@ -27333,12 +27648,12 @@
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
case 151 /* 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 === 289 /* 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 === 294 /* 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;
@@ -27422,13 +27737,15 @@
message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
messageNeedsName_1 = false;
}
- if (symbol.declarations && symbol.declarations.length) {
+ var multipleDefaultExports_1 = false;
+ if (ts.length(symbol.declarations)) {
// If the current node is a default export of some sort, then check if
// there are any other default exports that we need to error on.
// 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;
+ multipleDefaultExports_1 = true;
}
else {
// This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
@@ -27439,14 +27756,22 @@
(node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) {
message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
messageNeedsName_1 = false;
+ multipleDefaultExports_1 = true;
}
}
}
- 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);
+ var declarationName_1 = ts.getNameOfDeclaration(node) || node;
+ var relatedInformation_1 = [];
+ ts.forEach(symbol.declarations, function (declaration, index) {
+ var decl = ts.getNameOfDeclaration(declaration) || declaration;
+ var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
+ file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo(diag, createDiagnosticForNode(declarationName_1, index === 0 ? ts.Diagnostics.Another_export_default_is_here : ts.Diagnostics.and_here)) : diag);
+ if (multipleDefaultExports_1) {
+ relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
+ }
+ });
+ var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
+ file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInformation_1)) : diag);
symbol = createSymbol(0 /* None */, name);
}
}
@@ -27562,7 +27887,7 @@
}
}
// We create a return control flow graph for IIFEs and constructors. For constructors
- // we use the return control flow graph in strict property intialization checks.
+ // we use the return control flow graph in strict property initialization checks.
currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined;
currentBreakTarget = undefined;
currentContinueTarget = undefined;
@@ -27577,7 +27902,7 @@
if (hasExplicitReturn)
node.flags |= 256 /* HasExplicitReturn */;
}
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
node.flags |= emitFlags;
}
if (currentReturnTarget) {
@@ -27721,12 +28046,12 @@
case 191 /* CallExpression */:
bindCallExpressionFlow(node);
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
bindJSDocTypeAlias(node);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
- case 279 /* SourceFile */: {
+ case 284 /* SourceFile */: {
bindEachFunctionsFirst(node.statements);
bind(node.endOfFileToken);
break;
@@ -28413,7 +28738,7 @@
case 243 /* EnumDeclaration */:
case 188 /* ObjectLiteralExpression */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 268 /* JsxAttributes */:
return 1 /* IsContainer */;
case 241 /* InterfaceDeclaration */:
@@ -28422,7 +28747,7 @@
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
return 1 /* IsContainer */ | 32 /* HasLocals */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
case 156 /* MethodDeclaration */:
if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
@@ -28435,8 +28760,8 @@
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
- case 289 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
case 165 /* FunctionType */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
@@ -28490,7 +28815,7 @@
// handlers to take care of declaring these child members.
case 244 /* ModuleDeclaration */:
return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return declareSourceFileMember(node, symbolFlags, symbolExcludes);
case 209 /* ClassExpression */:
case 240 /* ClassDeclaration */:
@@ -28498,7 +28823,7 @@
case 243 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 188 /* ObjectLiteralExpression */:
case 241 /* InterfaceDeclaration */:
case 268 /* JsxAttributes */:
@@ -28512,7 +28837,7 @@
case 166 /* ConstructorType */:
case 160 /* CallSignature */:
case 161 /* ConstructSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 162 /* IndexSignature */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
@@ -28522,9 +28847,9 @@
case 239 /* FunctionDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
- case 289 /* JSDocFunctionType */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 294 /* JSDocFunctionType */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
// All the children of these container types are never visible through another
@@ -28547,8 +28872,8 @@
: declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node) {
- var body = node.kind === 279 /* SourceFile */ ? node : node.body;
- if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
+ var body = node.kind === 284 /* SourceFile */ ? node : node.body;
+ if (body && (body.kind === 284 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
var stat = _a[_i];
if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) {
@@ -28682,7 +29007,7 @@
case 244 /* ModuleDeclaration */:
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalOrCommonJsModule(container)) {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
@@ -28820,7 +29145,7 @@
function checkStrictModeFunctionDeclaration(node) {
if (languageVersion < 2 /* ES2015 */) {
// Report error if function is not top level function declaration
- if (blockScopeContainer.kind !== 279 /* SourceFile */ &&
+ if (blockScopeContainer.kind !== 284 /* SourceFile */ &&
blockScopeContainer.kind !== 244 /* ModuleDeclaration */ &&
!ts.isFunctionLike(blockScopeContainer)) {
// We check first if the name is inside class declaration or class expression; if so give explicit message
@@ -29095,12 +29420,12 @@
case 159 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */);
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
case 166 /* ConstructorType */:
return bindFunctionOrConstructorType(node);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 181 /* MappedType */:
return bindAnonymousTypeWorker(node);
case 188 /* ObjectLiteralExpression */:
@@ -29159,7 +29484,7 @@
return bindExportDeclaration(node);
case 254 /* ExportAssignment */:
return bindExportAssignment(node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
updateStrictModeStatementList(node.statements);
return bindSourceFileIfExternalModule();
case 218 /* Block */:
@@ -29169,22 +29494,22 @@
// falls through
case 245 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
- case 299 /* JSDocParameterTag */:
- if (node.parent.kind === 293 /* JSDocSignature */) {
+ case 304 /* JSDocParameterTag */:
+ if (node.parent.kind === 298 /* JSDocSignature */) {
return bindParameter(node);
}
- if (node.parent.kind !== 292 /* JSDocTypeLiteral */) {
+ if (node.parent.kind !== 297 /* JSDocTypeLiteral */) {
break;
}
// falls through
- case 305 /* JSDocPropertyTag */:
+ case 310 /* JSDocPropertyTag */:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 293 /* JSDocOptionalType */ ?
4 /* Property */ | 16777216 /* Optional */ :
4 /* Property */;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
}
}
@@ -29356,9 +29681,14 @@
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 279 /* SourceFile */:
- // this.foo assignment in a source file
- // Do not bind. It would be nice to support this someday though.
+ case 284 /* SourceFile */:
+ // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
+ if (thisContainer.commonJsModuleIndicator) {
+ declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220414 /* FunctionScopedVariableExcludes */);
+ }
break;
default:
ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer));
@@ -29368,7 +29698,7 @@
if (node.expression.kind === 100 /* ThisKeyword */) {
bindThisPropertyAssignment(node);
}
- else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) {
+ else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 284 /* SourceFile */) {
if (ts.isPrototypeAccess(node.expression)) {
bindPrototypePropertyAssignment(node, node.parent);
}
@@ -29405,7 +29735,7 @@
}
function bindObjectDefinePropertyAssignment(node) {
var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
- var isToplevel = node.parent.parent.kind === 279 /* SourceFile */;
+ var isToplevel = node.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false);
bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
}
@@ -29472,8 +29802,8 @@
function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
var namespaceSymbol = lookupSymbolForPropertyAccess(name);
var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
- ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */
- : propertyAccess.parent.parent.kind === 279 /* SourceFile */;
+ ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 284 /* SourceFile */
+ : propertyAccess.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty);
bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
}
@@ -29611,7 +29941,7 @@
}
}
function bindParameter(node) {
- if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) {
+ if (node.kind === 304 /* JSDocParameterTag */ && container.kind !== 298 /* JSDocSignature */) {
return;
}
if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) {
@@ -29869,44 +30199,37 @@
ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
function computeCallExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
+ var callee = ts.skipOuterExpressions(node.expression);
var expression = node.expression;
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */
- || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) {
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) {
// If the this node contains a SpreadExpression, or is a super call, then it is an ES6
// node.
- transformFlags |= 192 /* AssertES2015 */;
- // super property or element accesses could be inside lambdas, etc, and need a captured `this`,
- // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor)
- if (expression.transformFlags & 67108864 /* ContainsSuper */) {
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 128 /* AssertES2015 */;
+ if (ts.isSuperProperty(callee)) {
+ transformFlags |= 2048 /* ContainsLexicalThis */;
}
}
if (expression.kind === 92 /* ImportKeyword */) {
- transformFlags |= 16777216 /* ContainsDynamicImport */;
- // A dynamic 'import()' call that contains a lexical 'this' will
- // require a captured 'this' when emitting down-level.
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- transformFlags |= 16384 /* ContainsCapturedLexicalThis */;
- }
+ transformFlags |= 524288 /* ContainsDynamicImport */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */;
}
function computeNewExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */) {
// If the this node contains a SpreadElementExpression then it is an ES6
// node.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */;
}
function computeBinaryExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -29914,20 +30237,20 @@
var leftKind = node.left.kind;
if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) {
// Destructuring object assignments with are ES2015 syntax
- // and possibly ESNext if they contain rest
- transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
+ // and possibly ES2018 if they contain rest
+ transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */;
}
else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) {
// Destructuring assignments are ES2015 syntax.
- transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
+ transformFlags |= 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */;
}
else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */
|| operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) {
// Exponentiation is ES2016 syntax.
- transformFlags |= 32 /* AssertES2016 */;
+ transformFlags |= 64 /* AssertES2016 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeParameter(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -29938,147 +30261,131 @@
// syntax.
if (node.questionToken
|| node.type
- || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
+ || (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
|| ts.isThisIdentifier(name)) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// If a parameter has an accessibility modifier, then it is TypeScript syntax.
if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
- transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */;
}
- // parameters with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // parameters with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a parameter has an initializer, a binding pattern or a dotDotDot token, then
// it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
- if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
- transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */;
+ if (subtreeFlags & 65536 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* ParameterExcludes */;
+ return transformFlags & ~536870912 /* ParameterExcludes */;
}
function computeParenthesizedExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
var expression = node.expression;
var expressionKind = expression.kind;
- var expressionTransformFlags = expression.transformFlags;
// 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 === 212 /* AsExpression */
|| expressionKind === 194 /* TypeAssertionExpression */) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- // If the expression of a ParenthesizedExpression is a destructuring assignment,
- // then the ParenthesizedExpression is a destructuring assignment.
- if (expressionTransformFlags & 1024 /* DestructuringAssignment */) {
- transformFlags |= 1024 /* DestructuringAssignment */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536872257 /* OuterExpressionExcludes */;
+ return transformFlags & ~536870912 /* OuterExpressionExcludes */;
}
function computeClassDeclaration(node, subtreeFlags) {
var transformFlags;
if (ts.hasModifier(node, 2 /* Ambient */)) {
// An ambient declaration is TypeScript syntax.
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
// A ClassDeclaration is ES6 syntax.
- transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// A class with a parameter property assignment, property initializer, computed property name, or decorator is
// TypeScript syntax.
// An exported declaration may be TypeScript syntax, but is handled by the visitor
// for a namespace declaration.
- if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */)
+ if ((subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */)
|| node.typeParameters) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~638121281 /* ClassExcludes */;
+ return transformFlags & ~536888320 /* ClassExcludes */;
}
function computeClassExpression(node, subtreeFlags) {
// A ClassExpression is ES6 syntax.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// A class with a parameter property assignment, property initializer, or decorator is
// TypeScript syntax.
- if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */
+ if (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */
|| node.typeParameters) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~638121281 /* ClassExcludes */;
+ return transformFlags & ~536888320 /* ClassExcludes */;
}
function computeHeritageClause(node, subtreeFlags) {
var transformFlags = subtreeFlags;
switch (node.token) {
case 86 /* ExtendsKeyword */:
// An `extends` HeritageClause is ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 109 /* ImplementsKeyword */:
// An `implements` HeritageClause is TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
break;
default:
ts.Debug.fail("Unexpected token for heritage clause");
break;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeCatchClause(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (!node.variableDeclaration) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 8 /* AssertES2019 */;
}
else if (ts.isBindingPattern(node.variableDeclaration.name)) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637797697 /* CatchClauseExcludes */;
+ return transformFlags & ~536879104 /* CatchClauseExcludes */;
}
function computeExpressionWithTypeArguments(node, subtreeFlags) {
// An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
// extends clause of a class.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// If an ExpressionWithTypeArguments contains type arguments, then it
// is TypeScript syntax.
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeConstructor(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// TypeScript-specific modifiers and overloads are TypeScript syntax
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* ConstructorExcludes */;
+ return transformFlags & ~537372672 /* ConstructorExcludes */;
}
function computeMethod(node, subtreeFlags) {
// A MethodDeclaration is ES6 syntax.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
// overloads are TypeScript syntax.
if (node.decorators
@@ -30087,21 +30394,21 @@
|| node.type
|| (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// An async method declaration is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* MethodOrAccessorExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */);
}
function computeAccessor(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -30112,25 +30419,25 @@
|| node.type
|| (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* MethodOrAccessorExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */);
}
function computePropertyDeclaration(node, subtreeFlags) {
// A PropertyDeclaration is TypeScript syntax.
- var transformFlags = subtreeFlags | 3 /* AssertTypeScript */;
+ var transformFlags = subtreeFlags | 1 /* AssertTypeScript */;
// If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor
// so that it handle the transformation.
if (node.initializer || ts.isComputedPropertyName(node.name)) {
- transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1024 /* ContainsTypeScriptClassSyntax */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~536872960 /* PropertyExcludes */);
}
function computeFunctionDeclaration(node, subtreeFlags) {
var transformFlags;
@@ -30139,42 +30446,36 @@
if (!body || (modifierFlags & 2 /* Ambient */)) {
// An ambient declaration is TypeScript syntax.
// A FunctionDeclaration without a body is an overload and is TypeScript syntax.
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
- transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */;
+ transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */;
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (modifierFlags & 2270 /* TypeScriptModifier */
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async function declaration is ES2017 syntax.
if (modifierFlags & 256 /* Async */) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If a FunctionDeclaration's subtree has marked the container as needing to capture the
- // lexical this, or the function contains parameters with initializers, then this node is
- // ES6 syntax.
- if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) {
- transformFlags |= 192 /* AssertES2015 */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a FunctionDeclaration is generator function and is the body of a
// transformed async function, then this node can be transformed to a
// down-level generator.
- // Currently we do not support transforming any other generator fucntions
+ // Currently we do not support transforming any other generator functions
// down level.
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653620545 /* FunctionExcludes */;
+ return transformFlags & ~537373696 /* FunctionExcludes */;
}
function computeFunctionExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -30183,181 +30484,161 @@
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async function expression is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
- // function expressions with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If a FunctionExpression's subtree has marked the container as needing to capture the
- // lexical this, or the function contains parameters with initializers, then this node is
- // ES6 syntax.
- if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) {
- transformFlags |= 192 /* AssertES2015 */;
+ // function expressions with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a FunctionExpression is generator function and is the body of a
// transformed async function, then this node can be transformed to a
// down-level generator.
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653620545 /* FunctionExcludes */;
+ return transformFlags & ~537373696 /* FunctionExcludes */;
}
function computeArrowFunction(node, subtreeFlags) {
// An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async arrow function is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= 16 /* AssertES2017 */;
+ transformFlags |= 32 /* AssertES2017 */;
}
- // arrow functions with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If an ArrowFunction contains a lexical this, its container must capture the lexical this.
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- transformFlags |= 16384 /* ContainsCapturedLexicalThis */;
+ // arrow functions with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653604161 /* ArrowFunctionExcludes */;
+ return transformFlags & ~537371648 /* ArrowFunctionExcludes */;
}
function computePropertyAccess(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// If a PropertyAccessExpression starts with a super keyword, then it is
// ES6 syntax, and requires a lexical `this` binding.
- if (transformFlags & 33554432 /* Super */) {
- transformFlags ^= 33554432 /* Super */;
+ if (node.expression.kind === 98 /* SuperKeyword */) {
// super inside of an async function requires hoisting the super access (ES2017).
- // same for super inside of an async generator, which is ESNext.
- transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */;
+ // same for super inside of an async generator, which is ES2018.
+ transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~570426689 /* PropertyAccessExcludes */;
+ return transformFlags & ~536870912 /* PropertyAccessExcludes */;
}
function computeElementAccess(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- var expression = node.expression;
- var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing
// If an ElementAccessExpression starts with a super keyword, then it is
// ES6 syntax, and requires a lexical `this` binding.
- if (expressionFlags & 33554432 /* Super */) {
- transformFlags &= ~33554432 /* Super */;
+ if (node.expression.kind === 98 /* SuperKeyword */) {
// super inside of an async function requires hoisting the super access (ES2017).
- // same for super inside of an async generator, which is ESNext.
- transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */;
+ // same for super inside of an async generator, which is ES2018.
+ transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~570426689 /* PropertyAccessExcludes */;
+ return transformFlags & ~536870912 /* PropertyAccessExcludes */;
}
function computeVariableDeclaration(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- // A VariableDeclaration containing ObjectRest is ESNext syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally?
+ // A VariableDeclaration containing ObjectRest is ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// Type annotations are TypeScript syntax.
if (node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeVariableStatement(node, subtreeFlags) {
var transformFlags;
var declarationListTransformFlags = node.declarationList.transformFlags;
// An ambient declaration is TypeScript syntax.
if (ts.hasModifier(node, 2 /* Ambient */)) {
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
transformFlags = subtreeFlags;
- if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) {
- transformFlags |= 192 /* AssertES2015 */;
+ if (declarationListTransformFlags & 65536 /* ContainsBindingPattern */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeLabeledStatement(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
- if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */
+ if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */
&& ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeImportEquals(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// An ImportEqualsDeclaration with a namespace reference is TypeScript.
if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeExpressionStatement(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- // If the expression of an expression statement is a destructuring assignment,
- // then we treat the statement as ES6 so that we can indicate that we do not
- // need to hold on to the right-hand side.
- if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) {
- transformFlags |= 192 /* AssertES2015 */;
- }
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeModuleDeclaration(node, subtreeFlags) {
- var transformFlags = 3 /* AssertTypeScript */;
+ var transformFlags = 1 /* AssertTypeScript */;
var modifierFlags = ts.getModifierFlags(node);
if ((modifierFlags & 2 /* Ambient */) === 0) {
transformFlags |= subtreeFlags;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~647001409 /* ModuleExcludes */;
+ return transformFlags & ~537168896 /* ModuleExcludes */;
}
function computeVariableDeclarationList(node, subtreeFlags) {
- var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */;
- if (subtreeFlags & 2097152 /* ContainsBindingPattern */) {
- transformFlags |= 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */;
+ if (subtreeFlags & 65536 /* ContainsBindingPattern */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
// If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
if (node.flags & 3 /* BlockScoped */) {
- transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */;
+ transformFlags |= 128 /* AssertES2015 */ | 32768 /* ContainsBlockScopedBinding */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~639894849 /* VariableDeclarationListExcludes */;
+ return transformFlags & ~536944640 /* VariableDeclarationListExcludes */;
}
function computeOther(node, kind, subtreeFlags) {
// Mark transformations needed for each node
var transformFlags = subtreeFlags;
- var excludeFlags = 637535553 /* NodeExcludes */;
+ var excludeFlags = 536870912 /* NodeExcludes */;
switch (kind) {
case 121 /* AsyncKeyword */:
case 201 /* AwaitExpression */:
- // async/await is ES2017 syntax, but may be ESNext syntax (for async generators)
- transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */;
+ // async/await is ES2017 syntax, but may be ES2018 syntax (for async generators)
+ transformFlags |= 16 /* AssertES2018 */ | 32 /* AssertES2017 */;
break;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
// These nodes are TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
- excludeFlags = 536872257 /* OuterExpressionExcludes */;
+ transformFlags |= 1 /* AssertTypeScript */;
+ excludeFlags = 536870912 /* OuterExpressionExcludes */;
break;
case 115 /* PublicKeyword */:
case 113 /* PrivateKeyword */:
@@ -30370,7 +30651,7 @@
case 213 /* NonNullExpression */:
case 133 /* ReadonlyKeyword */:
// These nodes are TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
break;
case 260 /* JsxElement */:
case 261 /* JsxSelfClosingElement */:
@@ -30385,7 +30666,7 @@
case 269 /* JsxSpreadAttribute */:
case 270 /* JsxExpression */:
// These nodes are Jsx syntax.
- transformFlags |= 4 /* AssertJsx */;
+ transformFlags |= 2 /* AssertJsx */;
break;
case 14 /* NoSubstitutionTemplateLiteral */:
case 15 /* TemplateHead */:
@@ -30397,32 +30678,32 @@
case 116 /* StaticKeyword */:
case 214 /* MetaProperty */:
// These nodes are ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 10 /* StringLiteral */:
if (node.hasExtendedUnicodeEscape) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
case 8 /* NumericLiteral */:
if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
case 9 /* BigIntLiteral */:
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 4 /* AssertESNext */;
break;
case 227 /* ForOfStatement */:
// This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
if (node.awaitModifier) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 16 /* AssertES2018 */;
}
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 207 /* YieldExpression */:
// This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
// generator).
- transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */;
+ transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 131072 /* ContainsYield */;
break;
case 120 /* AnyKeyword */:
case 135 /* NumberKeyword */:
@@ -30463,115 +30744,93 @@
case 182 /* LiteralType */:
case 247 /* NamespaceExportDeclaration */:
// Types and signatures are TypeScript syntax, and exclude all other facts.
- transformFlags = 3 /* AssertTypeScript */;
- excludeFlags = -3 /* TypeExcludes */;
+ transformFlags = 1 /* AssertTypeScript */;
+ excludeFlags = -2 /* TypeExcludes */;
break;
case 149 /* ComputedPropertyName */:
// Even though computed property names are ES6, we don't treat them as such.
// This is so that they can flow through PropertyName transforms unaffected.
// Instead, we mark the container as ES6, so that it can properly handle the transform.
- transformFlags |= 524288 /* ContainsComputedPropertyName */;
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- // A computed method name like `[this.getName()](x: string) { ... }` needs to
- // distinguish itself from the normal case of a method body containing `this`:
- // `this` inside a method doesn't need to be rewritten (the method provides `this`),
- // whereas `this` inside a computed name *might* need to be rewritten if the class/object
- // is inside an arrow function:
- // `_this = this; () => class K { [_this.getName()]() { ... } }`
- // To make this distinction, use ContainsLexicalThisInComputedPropertyName
- // instead of ContainsLexicalThis for computed property names
- transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */;
- }
+ transformFlags |= 16384 /* ContainsComputedPropertyName */;
break;
case 208 /* SpreadElement */:
- transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */;
+ transformFlags |= 128 /* AssertES2015 */ | 4096 /* ContainsRestOrSpread */;
break;
case 277 /* SpreadAssignment */:
- transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */;
+ transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */;
break;
case 98 /* SuperKeyword */:
// This node is ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */;
- excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super`
+ transformFlags |= 128 /* AssertES2015 */;
+ excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super`
break;
case 100 /* ThisKeyword */:
// Mark this node and its ancestors as containing a lexical `this` keyword.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 2048 /* ContainsLexicalThis */;
break;
case 184 /* ObjectBindingPattern */:
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */;
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */;
}
- excludeFlags = 637666625 /* BindingPatternExcludes */;
+ excludeFlags = 536875008 /* BindingPatternExcludes */;
break;
case 185 /* ArrayBindingPattern */:
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- excludeFlags = 637666625 /* BindingPatternExcludes */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */;
+ excludeFlags = 536875008 /* BindingPatternExcludes */;
break;
case 186 /* BindingElement */:
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
if (node.dotDotDotToken) {
- transformFlags |= 131072 /* ContainsRestOrSpread */;
+ transformFlags |= 4096 /* ContainsRestOrSpread */;
}
break;
case 152 /* Decorator */:
// This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */;
break;
case 188 /* ObjectLiteralExpression */:
- excludeFlags = 638358849 /* ObjectLiteralExcludes */;
- if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) {
+ excludeFlags = 536896512 /* ObjectLiteralExcludes */;
+ if (subtreeFlags & 16384 /* ContainsComputedPropertyName */) {
// If an ObjectLiteralExpression contains a ComputedPropertyName, then it
// is an ES6 node.
- transformFlags |= 192 /* AssertES2015 */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 128 /* AssertES2015 */;
}
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
// If an ObjectLiteralExpression contains a spread element, then it
- // is an ES next node.
- transformFlags |= 8 /* AssertESNext */;
+ // is an ES2018 node.
+ transformFlags |= 16 /* AssertES2018 */;
}
break;
case 187 /* ArrayLiteralExpression */:
- case 192 /* NewExpression */:
- excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */;
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
- // If the this node contains a SpreadExpression, then it is an ES6
- // node.
- transformFlags |= 192 /* AssertES2015 */;
- }
+ excludeFlags = 536875008 /* ArrayLiteralOrCallOrNewExcludes */;
break;
case 223 /* DoStatement */:
case 224 /* WhileStatement */:
case 225 /* ForStatement */:
case 226 /* ForInStatement */:
// A loop containing a block scoped binding *may* need to be transformed from ES6.
- if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) {
- transformFlags |= 192 /* AssertES2015 */;
+ if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
- case 279 /* SourceFile */:
- if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) {
- transformFlags |= 192 /* AssertES2015 */;
- }
+ case 284 /* SourceFile */:
break;
case 230 /* ReturnStatement */:
- // Return statements may require an `await` in ESNext.
- transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */;
+ // Return statements may require an `await` in ES2018.
+ transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */ | 16 /* AssertES2018 */;
break;
case 228 /* ContinueStatement */:
case 229 /* BreakStatement */:
- transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */;
+ transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */;
break;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
return transformFlags & ~excludeFlags;
}
+ function propagatePropertyNameFlags(node, transformFlags) {
+ return transformFlags | (node.transformFlags & 2048 /* PropertyNamePropagatingFlags */);
+ }
/**
* Gets the transform flags to exclude when unioning the transform flags of a subtree.
*
@@ -30581,33 +30840,33 @@
*/
function getTransformFlagsSubtreeExclusions(kind) {
if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) {
- return -3 /* TypeExcludes */;
+ return -2 /* TypeExcludes */;
}
switch (kind) {
case 191 /* CallExpression */:
case 192 /* NewExpression */:
case 187 /* ArrayLiteralExpression */:
- return 637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return 536875008 /* ArrayLiteralOrCallOrNewExcludes */;
case 244 /* ModuleDeclaration */:
- return 647001409 /* ModuleExcludes */;
+ return 537168896 /* ModuleExcludes */;
case 151 /* Parameter */:
- return 637535553 /* ParameterExcludes */;
+ return 536870912 /* ParameterExcludes */;
case 197 /* ArrowFunction */:
- return 653604161 /* ArrowFunctionExcludes */;
+ return 537371648 /* ArrowFunctionExcludes */;
case 196 /* FunctionExpression */:
case 239 /* FunctionDeclaration */:
- return 653620545 /* FunctionExcludes */;
+ return 537373696 /* FunctionExcludes */;
case 238 /* VariableDeclarationList */:
- return 639894849 /* VariableDeclarationListExcludes */;
+ return 536944640 /* VariableDeclarationListExcludes */;
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
- return 638121281 /* ClassExcludes */;
+ return 536888320 /* ClassExcludes */;
case 157 /* Constructor */:
- return 653616449 /* ConstructorExcludes */;
+ return 537372672 /* ConstructorExcludes */;
case 156 /* MethodDeclaration */:
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
- return 653616449 /* MethodOrAccessorExcludes */;
+ return 537372672 /* MethodOrAccessorExcludes */;
case 120 /* AnyKeyword */:
case 135 /* NumberKeyword */:
case 146 /* BigIntKeyword */:
@@ -30625,25 +30884,25 @@
case 162 /* IndexSignature */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- return -3 /* TypeExcludes */;
+ return -2 /* TypeExcludes */;
case 188 /* ObjectLiteralExpression */:
- return 638358849 /* ObjectLiteralExcludes */;
+ return 536896512 /* ObjectLiteralExcludes */;
case 274 /* CatchClause */:
- return 637797697 /* CatchClauseExcludes */;
+ return 536879104 /* CatchClauseExcludes */;
case 184 /* ObjectBindingPattern */:
case 185 /* ArrayBindingPattern */:
- return 637666625 /* BindingPatternExcludes */;
+ return 536875008 /* BindingPatternExcludes */;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
case 195 /* ParenthesizedExpression */:
case 98 /* SuperKeyword */:
- return 536872257 /* OuterExpressionExcludes */;
+ return 536870912 /* OuterExpressionExcludes */;
case 189 /* PropertyAccessExpression */:
case 190 /* ElementAccessExpression */:
- return 570426689 /* PropertyAccessExcludes */;
+ return 536870912 /* PropertyAccessExcludes */;
default:
- return 637535553 /* NodeExcludes */;
+ return 536870912 /* NodeExcludes */;
}
}
ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
@@ -30892,6 +31151,7 @@
var enumCount = 0;
var instantiationDepth = 0;
var constraintDepth = 0;
+ var currentNode;
var emptySymbols = ts.createSymbolTable();
var identityMapper = ts.identity;
var compilerOptions = host.getCompilerOptions();
@@ -30908,8 +31168,14 @@
var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
var emitResolver = createResolver();
var nodeBuilder = createNodeBuilder();
+ var globals = ts.createSymbolTable();
var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
undefinedSymbol.declarations = [];
+ var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
+ globalThisSymbol.exports = globals;
+ globalThisSymbol.valueDeclaration = ts.createNode(72 /* Identifier */);
+ globalThisSymbol.valueDeclaration.escapedText = "globalThis";
+ globals.set(globalThisSymbol.escapedName, globalThisSymbol);
var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
var requireSymbol = createSymbol(4 /* Property */, "require");
/** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
@@ -31039,11 +31305,13 @@
isContextSensitive: isContextSensitive,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 0 /* Normal */);
},
getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */);
},
+ getExpandedParameters: getExpandedParameters,
+ hasEffectiveRestParameter: hasEffectiveRestParameter,
getConstantValue: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
return node ? getConstantValue(node) : undefined;
@@ -31105,6 +31373,8 @@
getNeverType: function () { return neverType; },
isSymbolAccessible: isSymbolAccessible,
getObjectFlags: ts.getObjectFlags,
+ isArrayType: isArrayType,
+ isTupleType: isTupleType,
isArrayLikeType: isArrayLikeType,
isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
@@ -31120,9 +31390,9 @@
getAccessibleSymbolChain: getAccessibleSymbolChain,
getTypePredicateOfSignature: getTypePredicateOfSignature,
resolveExternalModuleSymbol: resolveExternalModuleSymbol,
- tryGetThisTypeAt: function (node) {
+ tryGetThisTypeAt: function (node, includeGlobalThis) {
node = ts.getParseTreeNode(node);
- return node && tryGetThisTypeAt(node);
+ return node && tryGetThisTypeAt(node, includeGlobalThis);
},
getTypeArgumentConstraint: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
@@ -31169,10 +31439,10 @@
},
getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
};
- function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) {
+ function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
apparentArgumentCount = argumentCount;
- var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined;
+ var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
apparentArgumentCount = undefined;
return res;
}
@@ -31181,6 +31451,7 @@
var intersectionTypes = ts.createMap();
var literalTypes = ts.createMap();
var indexedAccessTypes = ts.createMap();
+ var conditionalTypes = ts.createMap();
var evolvingArrayTypes = [];
var undefinedProperties = ts.createMap();
var unknownSymbol = createSymbol(4 /* Property */, "unknown");
@@ -31191,9 +31462,9 @@
var errorType = createIntrinsicType(1 /* Any */, "error");
var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
- var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined");
+ var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */);
var nullType = createIntrinsicType(65536 /* Null */, "null");
- var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null");
+ var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */);
var stringType = createIntrinsicType(4 /* String */, "string");
var numberType = createIntrinsicType(8 /* Number */, "number");
var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
@@ -31219,6 +31490,7 @@
var voidType = createIntrinsicType(16384 /* Void */, "void");
var neverType = createIntrinsicType(131072 /* Never */, "never");
var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
+ var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */);
var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
@@ -31235,7 +31507,7 @@
var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
// The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
// in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
- anyFunctionType.flags |= 536870912 /* ContainsAnyFunctionType */;
+ anyFunctionType.objectFlags |= 524288 /* NonInferrableType */;
var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
@@ -31249,7 +31521,6 @@
var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
- var globals = ts.createSymbolTable();
/** Key is "/path/to/a.ts|/path/to/b.ts". */
var amalgamatedDuplicates;
var reverseMappedCache = ts.createMap();
@@ -31448,9 +31719,11 @@
var CheckMode;
(function (CheckMode) {
CheckMode[CheckMode["Normal"] = 0] = "Normal";
- CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive";
+ CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
- CheckMode[CheckMode["Contextual"] = 3] = "Contextual";
+ CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
+ CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
+ CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
})(CheckMode || (CheckMode = {}));
var CallbackCheck;
(function (CallbackCheck) {
@@ -31537,18 +31810,6 @@
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)
@@ -31728,7 +31989,7 @@
err.relatedInformation = err.relatedInformation || [];
if (ts.length(err.relatedInformation) >= 5)
continue;
- addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here));
+ ts.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) {
@@ -31806,7 +32067,7 @@
return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
}
function isGlobalSourceFile(node) {
- return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
+ return node.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning) {
@@ -31980,7 +32241,7 @@
// - 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 & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) {
+ if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 296 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -32022,14 +32283,14 @@
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
isInExternalModule = true;
// falls through
case 244 /* ModuleDeclaration */:
var moduleExports = getSymbolOfNode(location).exports;
- if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) {
+ if (location.kind === 284 /* 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 */)) {
@@ -32197,12 +32458,18 @@
// @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
// }
//
- if (location.parent && ts.isClassElement(location.parent)) {
+ // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
+ //
+ // type T = number;
+ // declare function y(x: T): any;
+ // @param(1 as T) // <-- T should resolve to the type alias outside of class C
+ // class C<T> {}
+ if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 240 /* ClassDeclaration */)) {
location = location.parent;
}
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
// js type aliases do not resolve names from their host, so skip past it
location = ts.getJSDocHost(location);
break;
@@ -32221,7 +32488,7 @@
}
if (!result) {
if (lastLocation) {
- ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */);
+ ts.Debug.assert(lastLocation.kind === 284 /* SourceFile */);
if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
return lastLocation.symbol;
}
@@ -32244,7 +32511,8 @@
!checkAndReportErrorForExtendingInterface(errorLocation) &&
!checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
!checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
- !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) {
+ !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
+ !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
var suggestion = void 0;
if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
@@ -32252,7 +32520,7 @@
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));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
}
}
}
@@ -32409,6 +32677,16 @@
}
return false;
}
+ function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
+ if (meaning & (67897832 /* Type */ & ~1920 /* Namespace */)) {
+ var symbol = resolveSymbol(resolveName(errorLocation, name, ~67897832 /* Type */ & 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
+ error(errorLocation, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here, ts.unescapeLeadingUnderscores(name));
+ return true;
+ }
+ }
+ return false;
+ }
function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) {
if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") {
@@ -32417,7 +32695,7 @@
}
var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
- var message = (name === "Promise" || name === "Symbol")
+ var message = isES2015OrLaterConstructorName(name)
? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later
: ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
@@ -32426,6 +32704,18 @@
}
return false;
}
+ function isES2015OrLaterConstructorName(n) {
+ switch (n) {
+ case "Promise":
+ case "Symbol":
+ case "Map":
+ case "WeakMap":
+ case "Set":
+ case "WeakSet":
+ return true;
+ }
+ return false;
+ }
function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) {
var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
@@ -32468,7 +32758,7 @@
}
}
if (diagnosticMessage) {
- addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
+ ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
}
}
}
@@ -32652,7 +32942,7 @@
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));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
}
}
else {
@@ -32972,22 +33262,14 @@
return undefined;
}
if (moduleNotFoundError) {
- // For relative paths, see if this was possibly a projectReference redirect
- if (ts.pathIsRelative(moduleReference)) {
- var sourceFile_1 = ts.getSourceFileOfNode(location);
- var redirects = sourceFile_1.redirectedReferences;
- if (redirects) {
- var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName));
- for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) {
- var ext = _a[_i];
- var probePath = normalizedTargetPath + ext;
- if (redirects.indexOf(probePath) >= 0) {
- error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath);
+ // See if this was possibly a projectReference redirect
+ if (resolvedModule) {
+ var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
+ if (redirect) {
+ error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
return undefined;
}
}
- }
- }
if (resolutionDiagnostic) {
error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
}
@@ -33054,7 +33336,7 @@
function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) {
var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
if (!dontResolveAlias && symbol) {
- if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) {
+ if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 284 /* SourceFile */)) {
var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
? "allowSyntheticDefaultImports"
: "esModuleInterop";
@@ -33327,9 +33609,11 @@
result.id = typeCount;
return result;
}
- function createIntrinsicType(kind, intrinsicName) {
+ function createIntrinsicType(kind, intrinsicName, objectFlags) {
+ if (objectFlags === void 0) { objectFlags = 0; }
var type = createType(kind);
type.intrinsicName = intrinsicName;
+ type.objectFlags = objectFlags;
return type;
}
function createBooleanType(trueFalseTypes) {
@@ -33400,7 +33684,7 @@
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
@@ -33640,10 +33924,10 @@
return node && getSymbolOfNode(node);
}
function hasExternalModuleSymbol(declaration) {
- return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isAmbientModule(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
- return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
var aliasesToMakeVisible;
@@ -34012,8 +34296,8 @@
context.inferTypeParameters = type.root.inferTypeParameters;
var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
context.inferTypeParameters = saveInferTypeParameters;
- var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context);
- var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context);
+ var trueTypeNode = typeToTypeNodeHelper(type.trueType, context);
+ var falseTypeNode = typeToTypeNodeHelper(type.falseType, context);
context.approximateLength += 15;
return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
}
@@ -34100,7 +34384,7 @@
var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
(symbol.parent || // is exported function symbol
ts.forEach(symbol.declarations, function (declaration) {
- return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
+ return declaration.parent.kind === 284 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
// typeof is allowed only for static/non local functions
@@ -34140,13 +34424,14 @@
}
function typeReferenceToTypeNode(type) {
var typeArguments = type.typeArguments || ts.emptyArray;
- if (type.target === globalArrayType) {
+ if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
if (context.flags & 2 /* WriteArrayAsGenericType */) {
var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
- return ts.createTypeReferenceNode("Array", [typeArgumentNode]);
+ return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
}
var elementType = typeToTypeNodeHelper(typeArguments[0], context);
- return ts.createArrayTypeNode(elementType);
+ var arrayType = ts.createArrayTypeNode(elementType);
+ return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, arrayType);
}
else if (type.target.objectFlags & 8 /* Tuple */) {
if (typeArguments.length > 0) {
@@ -34159,11 +34444,13 @@
ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
ts.createOptionalTypeNode(tupleConstituentNodes[i]);
}
- return ts.createTupleTypeNode(tupleConstituentNodes);
+ var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes);
+ return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
}
}
if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
- return ts.createTupleTypeNode([]);
+ var tupleTypeNode = ts.createTupleTypeNode([]);
+ return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
}
context.encounteredError = true;
return undefined; // TODO: GH#18217
@@ -34327,7 +34614,7 @@
context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
context.enclosingDeclaration = saveEnclosingDeclaration;
var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined;
- if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) {
+ if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
var signatures = getSignaturesOfType(propertyType, 0 /* Call */);
for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
var signature = signatures_1[_i];
@@ -34463,7 +34750,7 @@
var savedContextFlags = context.flags;
context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
- type.symbol.declarations[0] &&
+ type.symbol.declarations && type.symbol.declarations[0] &&
ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
typeParameterShadowsNameInScope(type, context);
var name = shouldUseGeneratedName
@@ -34482,7 +34769,7 @@
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */);
if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
- parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */);
+ parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 304 /* JSDocParameterTag */);
}
var parameterType = getTypeOfSymbol(parameterSymbol);
if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
@@ -34640,7 +34927,7 @@
return top;
}
function getSpecifierForModuleSymbol(symbol, context) {
- var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */);
+ var file = ts.getDeclarationOfKind(symbol, 284 /* SourceFile */);
if (file && file.moduleName !== undefined) {
// Use the amd name if it is available
return file.moduleName;
@@ -34893,7 +35180,7 @@
ts.isExternalModuleAugmentation(node.parent.parent);
}
function isDefaultBindingContext(location) {
- return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location);
+ return location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location);
}
function getNameOfSymbolFromNameType(symbol, context) {
var nameType = symbol.nameType;
@@ -34970,8 +35257,8 @@
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* 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));
@@ -34998,7 +35285,7 @@
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 !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
+ !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 284 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
return isGlobalSourceFile(parent);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
@@ -35040,7 +35327,7 @@
// Type parameters are always visible
case 150 /* TypeParameter */:
// Source file and namespace export are always visible
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 247 /* NamespaceExportDeclaration */:
return true;
// Export assignments do not create name bindings outside the module
@@ -35219,7 +35506,7 @@
if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
&& !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
&& isSpreadableProperty(prop)) {
- members.set(prop.escapedName, getSpreadSymbol(prop));
+ members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
}
}
var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
@@ -35288,17 +35575,8 @@
function getTypeForBindingElement(declaration) {
var pattern = declaration.parent;
var parentType = getTypeForBindingElementParent(pattern.parent);
- // If parent has the unknown (error) type, then so does this binding element
- if (parentType === errorType) {
- return errorType;
- }
- // If no type was specified or inferred for parent,
- // infer from the initializer of the binding element if one is present.
- // Otherwise, go with the undefined type of the parent.
- if (!parentType) {
- return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType;
- }
- if (isTypeAny(parentType)) {
+ // If no type or an any type was inferred for parent, infer that for the binding element
+ if (!parentType || isTypeAny(parentType)) {
return parentType;
}
// Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
@@ -35380,6 +35658,11 @@
if (optional === void 0) { optional = true; }
return strictNullChecks && optional ? getOptionalType(type) : type;
}
+ function isParameterOfContextuallyTypedFunction(node) {
+ return node.kind === 151 /* Parameter */ &&
+ (node.parent.kind === 196 /* FunctionExpression */ || node.parent.kind === 197 /* ArrowFunction */) &&
+ !!getContextualType(node.parent);
+ }
// Return the inferred type for a variable, parameter, or property declaration
function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
// A variable declared in a for..in statement is of type string, or of type keyof T when the
@@ -35455,8 +35738,9 @@
return containerObjectType;
}
}
- // Use the type of the initializer expression if one is present
- if (declaration.initializer) {
+ // Use the type of the initializer expression if one is present and the declaration is
+ // not a parameter of a contextually typed function
+ if (declaration.initializer && !isParameterOfContextuallyTypedFunction(declaration)) {
var type = checkDeclarationInitializer(declaration);
return addOptionality(type, isOptional);
}
@@ -35465,8 +35749,9 @@
// I.e <Elem attr /> is sugar for <Elem attr={true} />
return trueType;
}
- // If the declaration specifies a binding pattern, use the type implied by the binding pattern
- if (ts.isBindingPattern(declaration.name)) {
+ // If the declaration specifies a binding pattern and is not a parameter of a contextually
+ // typed function, use the type implied by the binding pattern
+ if (ts.isBindingPattern(declaration.name) && !isParameterOfContextuallyTypedFunction(declaration)) {
return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
}
// No type specified and nothing can be inferred
@@ -35522,7 +35807,7 @@
definedInConstructor = true;
}
}
- var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217
+ var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
type = getUnionType(sourceTypes, 2 /* Subtype */);
}
var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
@@ -35673,7 +35958,7 @@
function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
var members = ts.createSymbolTable();
var stringIndexInfo;
- var objectFlags = 128 /* ObjectLiteral */;
+ var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
ts.forEach(pattern.elements, function (e) {
var name = e.propertyName || e.name;
if (e.dotDotDotToken) {
@@ -35694,7 +35979,6 @@
members.set(symbol.escapedName, symbol);
});
var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
- result.flags |= 268435456 /* ContainsObjectLiteral */;
result.objectFlags |= objectFlags;
if (includePatternInType) {
result.pattern = pattern;
@@ -35778,7 +36062,16 @@
}
function getTypeOfVariableOrParameterOrProperty(symbol) {
var links = getSymbolLinks(symbol);
- return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol));
+ if (!links.type) {
+ var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
+ // For a contextually typed parameter it is possible that a type has already
+ // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
+ // to preserve this type.
+ if (!links.type) {
+ links.type = type;
+ }
+ }
+ return links.type;
}
function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
// Handle prototype property
@@ -35811,19 +36104,19 @@
}
return type_1;
}
- if (declaration.kind === 254 /* ExportAssignment */) {
- return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
- }
// Handle variable, parameter or property
if (!pushTypeResolution(symbol, 0 /* Type */)) {
// Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
if (symbol.flags & 512 /* ValueModule */) {
return getTypeOfFuncClassEnumModule(symbol);
}
- return errorType;
+ return reportCircularityError(symbol);
}
var type;
- if (ts.isInJSFile(declaration) &&
+ if (declaration.kind === 254 /* ExportAssignment */) {
+ type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
+ }
+ else if (ts.isInJSFile(declaration) &&
(ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) {
type = getWidenedTypeFromAssignmentDeclaration(symbol);
}
@@ -35878,7 +36171,7 @@
if (symbol.flags & 512 /* ValueModule */) {
return getTypeOfFuncClassEnumModule(symbol);
}
- type = reportCircularityError(symbol);
+ return reportCircularityError(symbol);
}
return type;
}
@@ -36056,15 +36349,19 @@
return links.type;
}
function reportCircularityError(symbol) {
+ var declaration = symbol.valueDeclaration;
// Check if variable has type annotation that circularly references the variable itself
- if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) {
+ if (ts.getEffectiveTypeAnnotationNode(declaration)) {
error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
return errorType;
}
- // Otherwise variable has initializer that circularly references the variable itself
- if (noImplicitAny) {
+ // Check if variable has initializer that circularly references the variable itself
+ if (noImplicitAny && (declaration.kind !== 151 /* Parameter */ || declaration.initializer)) {
error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
}
+ // Circularities could also result from parameters in function expressions that end up
+ // having themselves as contextual types following type argument inference. In those cases
+ // we have already reported an implicit any error so we don't report anything here.
return anyType;
}
function getTypeOfSymbol(symbol) {
@@ -36140,15 +36437,15 @@
case 155 /* MethodSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 308 /* JSDocTemplateTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 181 /* MappedType */:
case 175 /* ConditionalType */:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -36269,7 +36566,7 @@
ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
}
}
- addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
+ ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
}
return type.resolvedBaseConstructorType = errorType;
}
@@ -36280,7 +36577,7 @@
function getBaseTypes(type) {
if (!type.resolvedBaseTypes) {
if (type.objectFlags & 8 /* Tuple */) {
- type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))];
+ type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)];
}
else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
if (type.symbol.flags & 32 /* Class */) {
@@ -36645,7 +36942,7 @@
}
return false;
}
- /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */
+ /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
function isThislessTypeParameter(node) {
var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
return !constraint || isThislessType(constraint);
@@ -36688,6 +36985,8 @@
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
case 157 /* Constructor */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
return isThislessFunctionLikeDeclaration(declaration);
}
}
@@ -37019,8 +37318,18 @@
return sig;
}
function cloneSignature(sig) {
- return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
+ var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
/*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes);
+ result.target = sig.target;
+ result.mapper = sig.mapper;
+ return result;
+ }
+ function createUnionSignature(signature, unionSignatures) {
+ var result = cloneSignature(signature);
+ result.unionSignatures = unionSignatures;
+ result.target = undefined;
+ result.mapper = undefined;
+ return result;
}
function getExpandedParameters(sig) {
if (sig.hasRestParameter) {
@@ -37129,9 +37438,8 @@
var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */);
thisParameter = createSymbolWithType(signature.thisParameter, thisType);
}
- s = cloneSignature(signature);
+ s = createUnionSignature(signature, unionSignatures);
s.thisParameter = thisParameter;
- s.unionSignatures = unionSignatures;
}
(result || (result = [])).push(s);
}
@@ -37246,13 +37554,22 @@
function unionSpreadIndexInfos(info1, info2) {
return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
}
- function includeMixinType(type, types, index) {
+ function findMixins(types) {
+ var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
+ var mixinFlags = ts.map(types, isMixinConstructorType);
+ if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
+ var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
+ mixinFlags[firstMixinIndex] = false;
+ }
+ return mixinFlags;
+ }
+ function includeMixinType(type, types, mixinFlags, index) {
var mixedTypes = [];
for (var i = 0; i < types.length; i++) {
if (i === index) {
mixedTypes.push(type);
}
- else if (isMixinConstructorType(types[i])) {
+ else if (mixinFlags[i]) {
mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
}
}
@@ -37266,7 +37583,8 @@
var stringIndexInfo;
var numberIndexInfo;
var types = type.types;
- var mixinCount = ts.countWhere(types, isMixinConstructorType);
+ var mixinFlags = findMixins(types);
+ var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
var _loop_6 = function (i) {
var t = type.types[i];
// When an intersection type contains mixin constructor types, the construct signatures from
@@ -37274,12 +37592,12 @@
// other construct signatures in the intersection type. For example, the intersection type
// '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
// 'new(s: string) => A & B'.
- if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) {
+ if (!mixinFlags[i]) {
var signatures = getSignaturesOfType(t, 1 /* Construct */);
if (signatures.length && mixinCount > 0) {
signatures = ts.map(signatures, function (s) {
var clone = cloneSignature(s);
- clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i);
+ clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
return clone;
});
}
@@ -37323,6 +37641,15 @@
var stringIndexInfo = void 0;
if (symbol.exports) {
members = getExportsOfSymbol(symbol);
+ if (symbol === globalThisSymbol) {
+ var varsOnly_1 = ts.createMap();
+ members.forEach(function (p) {
+ if (!(p.flags & 418 /* BlockScoped */)) {
+ varsOnly_1.set(p.escapedName, p);
+ }
+ });
+ members = varsOnly_1;
+ }
}
setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
if (symbol.flags & 32 /* Class */) {
@@ -37622,7 +37949,7 @@
var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
- return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected);
+ return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
});
}
function getAllPossiblePropertiesOfTypes(types) {
@@ -37655,6 +37982,9 @@
return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
}
function getConstraintOfIndexedAccess(type) {
+ return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
+ }
+ function getConstraintFromIndexedAccess(type) {
var objectType = getConstraintOfType(type.objectType) || type.objectType;
if (objectType !== type.objectType) {
var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType);
@@ -37667,13 +37997,13 @@
}
function getDefaultConstraintOfConditionalType(type) {
if (!type.resolvedDefaultConstraint) {
- var rootTrueType = type.root.trueType;
- var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */)
- ? rootTrueType
- : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */
- ? rootTrueType.typeVariable
- : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]);
- type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]);
+ // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
+ // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
+ // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
+ // in effect treating `any` like `never` rather than `unknown` in this location.
+ var trueConstraint = getInferredTrueTypeFromConditionalType(type);
+ var falseConstraint = type.falseType;
+ type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
}
return type.resolvedDefaultConstraint;
}
@@ -37683,7 +38013,13 @@
// with its constraint. We do this because if the constraint is a union type it will be distributed
// over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
// removes 'undefined' from T.
- if (type.root.isDistributive) {
+ // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
+ // as the constraint for all type params (check type included) have been replace with `unknown`, which
+ // is going to produce even more false positive/negative results than the distribute constraint already does.
+ // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
+ // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
+ // likely doesn't need to exist.
+ if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
var simplified = getSimplifiedType(type.checkType);
var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
if (constraint && constraint !== type.checkType) {
@@ -37696,9 +38032,12 @@
}
return undefined;
}
- function getConstraintOfConditionalType(type) {
+ function getConstraintFromConditionalType(type) {
return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
}
+ function getConstraintOfConditionalType(type) {
+ return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
+ }
function getUnionConstraintOfIntersection(type, targetIsUnion) {
var constraints;
var hasDisjointDomainType = false;
@@ -37772,18 +38111,31 @@
if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
return circularConstraintType;
}
- if (constraintDepth === 50) {
+ if (constraintDepth >= 50) {
// We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
// very high likelyhood we're dealing with an infinite generic type that perpetually generates
// new type identities as we descend into it. We stop the recursion here and mark this type
// and the outer types as having circular constraints.
+ error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
nonTerminating = true;
return t.immediateBaseConstraint = noConstraintType;
}
constraintDepth++;
var result = computeBaseConstraint(getSimplifiedType(t));
constraintDepth--;
- if (!popTypeResolution() || nonTerminating) {
+ if (!popTypeResolution()) {
+ if (t.flags & 262144 /* TypeParameter */) {
+ var errorNode = getConstraintDeclaration(t);
+ if (errorNode) {
+ var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
+ if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
+ }
+ }
+ }
+ result = circularConstraintType;
+ }
+ if (nonTerminating) {
result = circularConstraintType;
}
t.immediateBaseConstraint = result || noConstraintType;
@@ -37825,8 +38177,11 @@
return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined;
}
if (t.flags & 16777216 /* Conditional */) {
- var constraint = getConstraintOfConditionalType(t);
- return constraint && getBaseConstraint(constraint);
+ var constraint = getConstraintFromConditionalType(t);
+ constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
+ var result = constraint && getBaseConstraint(constraint);
+ constraintDepth--;
+ return result;
}
if (t.flags & 33554432 /* Substitution */) {
return getBaseConstraint(t.substitute);
@@ -37887,7 +38242,7 @@
var typeVariable = getHomomorphicTypeVariable(type);
if (typeVariable) {
var constraint = getConstraintOfTypeParameter(typeVariable);
- if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) {
+ if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
var mapper = makeUnaryTypeMapper(typeVariable, constraint);
return instantiateType(type, combineTypeMappers(mapper, type.mapper));
}
@@ -37905,7 +38260,7 @@
t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
t.flags & 132 /* StringLike */ ? globalStringType :
t.flags & 296 /* NumberLike */ ? globalNumberType :
- t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) :
+ t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ESNext */) :
t.flags & 528 /* BooleanLike */ ? globalBooleanType :
t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
@@ -37913,7 +38268,7 @@
t;
}
function createUnionOrIntersectionProperty(containingType, name) {
- var props;
+ var propSet = ts.createMap();
var indexTypes;
var isUnion = containingType.flags & 1048576 /* Union */;
var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0;
@@ -37929,7 +38284,10 @@
var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
if (prop && !(modifiers & excludeModifiers)) {
commonFlags &= prop.flags;
- props = ts.appendIfUnique(props, prop);
+ var id = "" + getSymbolId(prop);
+ if (!propSet.has(id)) {
+ propSet.set(id, prop);
+ }
checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
(!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) |
(modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) |
@@ -37951,9 +38309,10 @@
}
}
}
- if (!props) {
+ if (!propSet.size) {
return undefined;
}
+ var props = ts.arrayFrom(propSet.values());
if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) {
return props[0];
}
@@ -38125,10 +38484,10 @@
function isJSDocOptionalParameter(node) {
return ts.isInJSFile(node) && (
// node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
- node.type && node.type.kind === 288 /* JSDocOptionalType */
+ node.type && node.type.kind === 293 /* JSDocOptionalType */
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -38162,7 +38521,7 @@
return false;
}
var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}
function createIdentifierTypePredicate(parameterName, parameterIndex, type) {
return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
@@ -38396,32 +38755,23 @@
}
}
signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
- createTypePredicateFromTypePredicateNode(type, signature.declaration) :
+ createTypePredicateFromTypePredicateNode(type, signature) :
jsdocPredicate || noTypePredicate;
}
ts.Debug.assert(!!signature.resolvedTypePredicate);
}
return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
}
- function createTypePredicateFromTypePredicateNode(node, func) {
+ function createTypePredicateFromTypePredicateNode(node, signature) {
var parameterName = node.parameterName;
var type = getTypeFromTypeNode(node.type);
if (parameterName.kind === 72 /* Identifier */) {
- return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type);
+ return createIdentifierTypePredicate(parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), 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 === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) {
- return i;
- }
- }
- return -1;
- }
function getReturnTypeOfSignature(signature) {
if (!signature.resolvedReturnType) {
if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
@@ -38493,8 +38843,19 @@
}
return undefined;
}
- function getSignatureInstantiation(signature, typeArguments, isJavascript) {
- return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ if (inferredTypeParameters) {
+ var returnSignature = getSingleCallSignature(getReturnTypeOfSignature(instantiatedSignature));
+ if (returnSignature) {
+ var newReturnSignature = cloneSignature(returnSignature);
+ newReturnSignature.typeParameters = inferredTypeParameters;
+ var newInstantiatedSignature = cloneSignature(instantiatedSignature);
+ newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
+ return newInstantiatedSignature;
+ }
+ }
+ return instantiatedSignature;
}
function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
@@ -38689,10 +39050,10 @@
for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
var type = types_5[_i];
if (!(type.flags & excludeKinds)) {
- result |= type.flags;
+ result |= ts.getObjectFlags(type);
}
}
- return result & 939524096 /* PropagatingFlags */;
+ return result & 917504 /* PropagatingFlags */;
}
function createTypeReference(target, typeArguments) {
var id = getTypeListId(typeArguments);
@@ -38700,7 +39061,7 @@
if (!type) {
type = createObjectType(4 /* Reference */, target.symbol);
target.instantiations.set(id, type);
- type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
+ type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
type.target = target;
type.typeArguments = typeArguments;
}
@@ -38866,7 +39227,7 @@
}
function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
- if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
+ if (symbol.valueDeclaration && symbol.valueDeclaration.parent && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
if (jsdocType) {
return jsdocType;
@@ -38887,6 +39248,9 @@
}
}
function getSubstitutionType(typeVariable, substitute) {
+ if (substitute.flags & 3 /* AnyOrUnknown */) {
+ return typeVariable;
+ }
var result = createType(33554432 /* Substitution */);
result.typeVariable = typeVariable;
result.substitute = substitute;
@@ -38902,7 +39266,7 @@
}
function getConstrainedTypeVariable(typeVariable, node) {
var constraints;
- while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) {
+ while (node && !ts.isStatement(node) && node.kind !== 296 /* JSDocComment */) {
var parent = node.parent;
if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) {
var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
@@ -39134,19 +39498,19 @@
function createIterableIteratorType(iteratedType) {
return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]);
}
- function createArrayType(elementType) {
- return createTypeFromGenericGlobalType(globalArrayType, [elementType]);
- }
- function createReadonlyArrayType(elementType) {
- return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]);
+ function createArrayType(elementType, readonly) {
+ return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
}
function getTypeFromArrayTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType));
+ links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType), isReadonlyTypeOperator(node.parent));
}
return links.resolvedType;
}
+ function isReadonlyTypeOperator(node) {
+ return ts.isTypeOperatorNode(node) && node.operator === 133 /* ReadonlyKeyword */;
+ }
// We represent tuple types as type references to synthesized generic interface types created by
// this function. The types are of the form:
//
@@ -39154,7 +39518,7 @@
//
// 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, minLength, hasRestElement, associatedNames) {
+ function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
var typeParameters;
var properties = [];
var maxLength = hasRestElement ? arity - 1 : arity;
@@ -39163,7 +39527,7 @@
for (var i = 0; i < arity; i++) {
var typeParameter = typeParameters[i] = createTypeParameter();
if (i < maxLength) {
- var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i);
+ var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
property.type = typeParameter;
properties.push(property);
}
@@ -39193,25 +39557,27 @@
type.declaredNumberIndexInfo = undefined;
type.minLength = minLength;
type.hasRestElement = hasRestElement;
+ type.readonly = readonly;
type.associatedNames = associatedNames;
return type;
}
- function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) {
- var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
+ function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
+ var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
var type = tupleTypes.get(key);
if (!type) {
- tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames));
+ tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames));
}
return type;
}
- function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) {
+ function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) {
if (minLength === void 0) { minLength = elementTypes.length; }
if (hasRestElement === void 0) { hasRestElement = false; }
+ if (readonly === void 0) { readonly = false; }
var arity = elementTypes.length;
if (arity === 1 && hasRestElement) {
- return createArrayType(elementTypes[0]);
+ return createArrayType(elementTypes[0], readonly);
}
- var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames);
+ var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames);
return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
}
function getTypeFromTupleTypeNode(node) {
@@ -39224,7 +39590,7 @@
var type = getTypeFromTypeNode(n);
return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type;
});
- links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1);
+ links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1, isReadonlyTypeOperator(node.parent));
}
return links.resolvedType;
}
@@ -39234,7 +39600,7 @@
// don't slice off rest element
index = Math.min(index, getTypeReferenceArity(type) - 1);
}
- return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index));
+ return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index));
}
function getTypeFromOptionalTypeNode(node) {
var type = getTypeFromTypeNode(node.type);
@@ -39292,12 +39658,14 @@
// intersections of unit types into 'never' upon construction, but deferring the reduction makes it
// easier to reason about their origin.
if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) {
- includes |= flags & ~939524096 /* ConstructionFlags */;
+ includes |= flags & 1835007 /* IncludesMask */;
+ if (flags & 66846720 /* StructuredOrInstantiable */)
+ includes |= 262144 /* IncludesStructuredOrInstantiable */;
if (type === wildcardType)
- includes |= 268435456 /* Wildcard */;
+ includes |= 4194304 /* IncludesWildcard */;
if (!strictNullChecks && flags & 98304 /* Nullable */) {
- if (!(flags & 134217728 /* ContainsWideningType */))
- includes |= 134217728 /* NonWideningType */;
+ if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */))
+ includes |= 2097152 /* IncludesNonWideningType */;
}
else {
var len = typeSet.length;
@@ -39318,17 +39686,6 @@
}
return includes;
}
- function isSubtypeOfAny(source, targets) {
- for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
- var target = targets_1[_i];
- if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
- !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
- isTypeDerivedFrom(source, target))) {
- return true;
- }
- }
- return false;
- }
function isSetOfLiteralsFromSameEnum(types) {
var first = types[0];
if (first.flags & 1024 /* EnumLiteral */) {
@@ -39343,18 +39700,43 @@
}
return false;
}
- function removeSubtypes(types) {
- if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) {
- return;
+ function removeSubtypes(types, primitivesOnly) {
+ var len = types.length;
+ if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
+ return true;
}
- var i = types.length;
+ var i = len;
+ var count = 0;
while (i > 0) {
i--;
- if (isSubtypeOfAny(types[i], types)) {
+ var source = types[i];
+ for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
+ var target = types_7[_i];
+ if (source !== target) {
+ if (count === 100000) {
+ // After 100000 subtype checks we estimate the remaining amount of work by assuming the
+ // same ratio of checks per element. If the estimated number of remaining type checks is
+ // greater than an upper limit we deem the union type too complex to represent. The
+ // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
+ // caps union types at 5000 unique literal types and 1000 unique object types.
+ var estimatedCount = (count / (len - i)) * len;
+ if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
+ error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
+ return false;
+ }
+ }
+ count++;
+ if (isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
+ !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
+ isTypeDerivedFrom(source, target))) {
ts.orderedRemoveItemAt(types, i);
+ break;
}
}
}
+ }
+ return true;
+ }
function removeRedundantLiteralTypes(types, includes) {
var i = types.length;
while (i > 0) {
@@ -39389,25 +39771,27 @@
var includes = addTypesToUnion(typeSet, 0, types);
if (unionReduction !== 0 /* None */) {
if (includes & 3 /* AnyOrUnknown */) {
- return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType;
+ return includes & 1 /* Any */ ? includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
}
switch (unionReduction) {
case 1 /* Literal */:
- if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) {
+ if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
removeRedundantLiteralTypes(typeSet, includes);
}
break;
case 2 /* Subtype */:
- removeSubtypes(typeSet);
+ if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
+ return errorType;
+ }
break;
}
if (typeSet.length === 0) {
- return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType :
- includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType :
+ return includes & 65536 /* Null */ ? includes & 2097152 /* IncludesNonWideningType */ ? nullType : nullWideningType :
+ includes & 32768 /* Undefined */ ? includes & 2097152 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
neverType;
}
}
- return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments);
+ return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments);
}
function getUnionTypePredicate(signatures) {
var first;
@@ -39444,7 +39828,7 @@
: !ts.isIdentifierTypePredicate(b);
}
// This function assumes the constituent type list is sorted and deduplicated.
- function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) {
+ function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
if (types.length === 0) {
return neverType;
}
@@ -39454,11 +39838,10 @@
var id = getTypeListId(types);
var type = unionTypes.get(id);
if (!type) {
- var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
- type = createType(1048576 /* Union */ | propagatedFlags);
+ type = createType(1048576 /* Union */);
unionTypes.set(id, type);
+ type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
type.types = types;
- type.primitiveTypesOnly = primitiveTypesOnly;
/*
Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
@@ -39484,16 +39867,16 @@
return addTypesToIntersection(typeSet, includes, type.types);
}
if (isEmptyAnonymousObjectType(type)) {
- if (!(includes & 536870912 /* EmptyObject */)) {
- includes |= 536870912 /* EmptyObject */;
+ if (!(includes & 8388608 /* IncludesEmptyObject */)) {
+ includes |= 8388608 /* IncludesEmptyObject */;
typeSet.push(type);
}
}
else {
- includes |= flags & ~939524096 /* ConstructionFlags */;
+ includes |= flags & 1835007 /* IncludesMask */;
if (flags & 3 /* AnyOrUnknown */) {
if (type === wildcardType)
- includes |= 268435456 /* Wildcard */;
+ includes |= 4194304 /* IncludesWildcard */;
}
else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) {
typeSet.push(type);
@@ -39504,8 +39887,8 @@
// Add the given types to the given type set. Order is preserved, freshness is removed from literal
// types, duplicates are removed, and nested types of the given kind are flattened into the set.
function addTypesToIntersection(typeSet, includes, types) {
- for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
- var type = types_7[_i];
+ for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
+ var type = types_8[_i];
includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
}
return includes;
@@ -39548,7 +39931,7 @@
// 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 & 1048576 /* Union */) && t.primitiveTypesOnly; });
+ var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); });
if (index < 0) {
return false;
}
@@ -39557,7 +39940,7 @@
// the unionTypes array.
while (i < types.length) {
var t = types[i];
- if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) {
+ if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) {
(unionTypes || (unionTypes = [types[index]])).push(t);
ts.orderedRemoveItemAt(types, i);
}
@@ -39586,7 +39969,7 @@
}
}
// Finally replace the first union with the result
- types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true);
+ types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */);
return true;
}
// We normalize combinations of intersection and union types based on the distributive property of the '&'
@@ -39606,7 +39989,7 @@
return neverType;
}
if (includes & 1 /* Any */) {
- return includes & 268435456 /* Wildcard */ ? wildcardType : anyType;
+ return includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType;
}
if (!strictNullChecks && includes & 98304 /* Nullable */) {
return includes & 32768 /* Undefined */ ? undefinedType : nullType;
@@ -39617,7 +40000,7 @@
includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
removeRedundantPrimitiveTypes(typeSet, includes);
}
- if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) {
+ if (includes & 8388608 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
}
if (typeSet.length === 0) {
@@ -39642,9 +40025,9 @@
var id = getTypeListId(typeSet);
var type = intersectionTypes.get(id);
if (!type) {
- var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */);
- type = createType(2097152 /* Intersection */ | propagatedFlags);
+ type = createType(2097152 /* Intersection */);
intersectionTypes.set(id, type);
+ type.objectFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */);
type.types = typeSet;
type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
type.aliasTypeArguments = aliasTypeArguments;
@@ -39699,7 +40082,7 @@
return neverType;
}
function getLiteralTypeFromProperties(type, include) {
- return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); }));
+ return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
}
function getNonEnumNumberIndexInfo(type) {
var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
@@ -39741,6 +40124,9 @@
? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
: errorType;
break;
+ case 133 /* ReadonlyKeyword */:
+ links.resolvedType = getTypeFromTypeNode(node.type);
+ break;
}
}
return links.resolvedType; // TODO: GH#18217
@@ -39843,7 +40229,10 @@
return anyType;
}
if (accessExpression && !isConstEnumObjectType(objectType)) {
- if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
+ if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
+ error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
+ }
+ else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
}
@@ -39895,7 +40284,7 @@
: accessNode;
}
function isGenericObjectType(type) {
- return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */);
+ return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 131072 /* GenericMappedType */);
}
function isGenericIndexType(type) {
return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */);
@@ -39941,12 +40330,15 @@
// that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
// construct the type Box<T[X]>.
if (isGenericMappedType(objectType)) {
- var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
- var templateMapper = combineTypeMappers(objectType.mapper, mapper);
- return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType);
+ return type.simplified = mapType(substituteIndexedMappedType(objectType, type.indexType), getSimplifiedType);
}
return type.simplified = type;
}
+ function substituteIndexedMappedType(objectType, index) {
+ var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
+ var templateMapper = combineTypeMappers(objectType.mapper, mapper);
+ return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
+ }
function getIndexedAccessType(objectType, indexType, accessNode, missingType) {
if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; }
if (objectType === wildcardType || indexType === wildcardType) {
@@ -40028,13 +40420,48 @@
function getActualTypeVariable(type) {
return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type;
}
+ /**
+ * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
+ */
+ function isIntersectionEmpty(type1, type2) {
+ return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
+ }
function getConditionalType(root, mapper) {
var checkType = instantiateType(root.checkType, mapper);
var extendsType = instantiateType(root.extendsType, mapper);
if (checkType === wildcardType || extendsType === wildcardType) {
return wildcardType;
}
- var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */);
+ var trueType = instantiateType(root.trueType, mapper);
+ var falseType = instantiateType(root.falseType, mapper);
+ var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType);
+ var result = conditionalTypes.get(instantiationId);
+ if (result) {
+ return result;
+ }
+ var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType);
+ conditionalTypes.set(instantiationId, newResult);
+ return newResult;
+ }
+ function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) {
+ // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
+ if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
+ if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
+ return trueType;
+ }
+ else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
+ return neverType;
+ }
+ }
+ else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
+ if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
+ return neverType;
+ }
+ else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
+ return falseType;
+ }
+ }
+ var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */);
var combinedMapper;
if (root.inferTypeParameters) {
var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
@@ -40044,25 +40471,25 @@
// types rules (i.e. proper contravariance) for inferences.
inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
}
- combinedMapper = combineTypeMappers(mapper, context);
+ combinedMapper = combineTypeMappers(mapper, context.mapper);
}
// Instantiate the extends type including inferences for 'infer T' type parameters
var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
// We attempt to resolve the conditional type only when the check and extends types are non-generic
- if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */)) {
+ if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */)) {
if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) {
- return instantiateType(root.trueType, mapper);
+ return trueType;
}
// Return union of trueType and falseType for 'any' since it matches anything
if (checkType.flags & 1 /* Any */) {
- return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]);
+ return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), falseType]);
}
- // Return falseType for a definitely false extends check. We check an instantations of the two
+ // Return falseType for a definitely false extends check. We check an instantiations of the two
// types with type parameters mapped to the wildcard type, the most permissive instantiations
// possible (the wildcard type is assignable to and from all types). If those are not related,
- // then no instatiations will be and we can just return the false branch type.
+ // then no instantiations will be and we can just return the false branch type.
if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) {
- return instantiateType(root.falseType, mapper);
+ return falseType;
}
// Return trueType for a definitely true extends check. We check instantiations of the two
// types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
@@ -40074,6 +40501,9 @@
}
}
// Return a deferred type for a check that is neither definitely true nor definitely false
+ return getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType);
+ }
+ function getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType) {
var erasedCheckType = getActualTypeVariable(checkType);
var result = createType(16777216 /* Conditional */);
result.root = root;
@@ -40081,15 +40511,14 @@
result.extendsType = extendsType;
result.mapper = mapper;
result.combinedMapper = combinedMapper;
+ result.trueType = trueType;
+ result.falseType = falseType;
result.aliasSymbol = root.aliasSymbol;
result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
return result;
}
- function getTrueTypeFromConditionalType(type) {
- return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
- }
- function getFalseTypeFromConditionalType(type) {
- return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
+ function getInferredTrueTypeFromConditionalType(type) {
+ return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper || type.mapper));
}
function getInferTypeParameters(node) {
var result;
@@ -40258,7 +40687,7 @@
* this function should be called in a left folding style, with left = previous result of getSpreadType
* and right = the new element to be spread.
*/
- function getSpreadType(left, right, symbol, typeFlags, objectFlags) {
+ function getSpreadType(left, right, symbol, objectFlags, readonly) {
if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
return anyType;
}
@@ -40272,10 +40701,10 @@
return left;
}
if (left.flags & 1048576 /* Union */) {
- return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); });
+ return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
}
if (right.flags & 1048576 /* Union */) {
- return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); });
+ return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
}
if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
return left;
@@ -40291,7 +40720,7 @@
var types = left.types;
var lastLeft = types[types.length - 1];
if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
- return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)]));
+ return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
}
}
return getIntersectionType([left, right]);
@@ -40315,7 +40744,7 @@
skippedPrivateMembers.set(rightProp.escapedName, true);
}
else if (isSpreadableProperty(rightProp)) {
- members.set(rightProp.escapedName, getSpreadSymbol(rightProp));
+ members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
}
}
for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
@@ -40339,12 +40768,11 @@
}
}
else {
- members.set(leftProp.escapedName, getSpreadSymbol(leftProp));
+ members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
}
}
- var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo));
- spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags;
- spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
+ var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
+ spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
return spread;
}
/** We approximate own properties as non-methods plus methods that are inside the object literal */
@@ -40352,25 +40780,21 @@
return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
!prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); });
}
- function getSpreadSymbol(prop) {
- var isReadonly = isReadonlySymbol(prop);
+ function getSpreadSymbol(prop, readonly) {
var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
- if (!isReadonly && !isSetonlyAccessor) {
+ if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
return prop;
}
var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
- var result = createSymbol(flags, prop.escapedName);
+ var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
result.declarations = prop.declarations;
result.nameType = prop.nameType;
result.syntheticOrigin = prop;
return result;
}
- function getNonReadonlyIndexSignature(index) {
- if (index && index.isReadonly) {
- return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration);
- }
- return index;
+ function getIndexInfoWithReadonly(info, readonly) {
+ return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
}
function createLiteralType(flags, value, symbol) {
var type = createType(flags);
@@ -40458,8 +40882,8 @@
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 120 /* AnyKeyword */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return anyType;
case 143 /* UnknownKeyword */:
return unknownType;
@@ -40506,23 +40930,23 @@
return getTypeFromUnionTypeNode(node);
case 174 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return getTypeFromJSDocNullableTypeNode(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return addOptionality(getTypeFromTypeNode(node.type));
case 177 /* ParenthesizedType */:
case 172 /* RestType */:
- case 287 /* JSDocNonNullableType */:
- case 283 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 288 /* JSDocTypeExpression */:
return getTypeFromTypeNode(node.type);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 297 /* JSDocTypeLiteral */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 179 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
@@ -40598,16 +41022,8 @@
* Maps forward-references to later types parameters to the empty object type.
* This is used during inference when instantiating type parameter defaults.
*/
- function createBackreferenceMapper(typeParameters, index) {
- return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; };
- }
- function isInferenceContext(mapper) {
- return !!mapper.typeParameters;
- }
- function cloneTypeMapper(mapper) {
- return mapper && isInferenceContext(mapper) ?
- createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) :
- mapper;
+ function createBackreferenceMapper(context, index) {
+ return function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? emptyObjectType : t; };
}
function combineTypeMappers(mapper1, mapper2) {
if (!mapper1)
@@ -40690,7 +41106,7 @@
}
// 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) & (2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */));
+ var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */));
result.declarations = symbol.declarations;
result.parent = symbol.parent;
result.target = symbol;
@@ -40786,7 +41202,7 @@
function getHomomorphicTypeVariable(type) {
var constraintType = getConstraintTypeFromMappedType(type);
if (constraintType.flags & 4194304 /* Index */) {
- var typeVariable = constraintType.type;
+ var typeVariable = getActualTypeVariable(constraintType.type);
if (typeVariable.flags & 262144 /* TypeParameter */) {
return typeVariable;
}
@@ -40808,30 +41224,27 @@
if (typeVariable) {
var mappedTypeVariable = instantiateType(typeVariable, mapper);
if (typeVariable !== mappedTypeVariable) {
- // If we are already in the process of creating an instantiation of this mapped type,
- // return the error type. This situation only arises if we are instantiating the mapped
- // type for an array or tuple type, as we then need to eagerly resolve the (possibly
- // circular) element type(s).
- if (type.instantiating) {
- return errorType;
- }
- type.instantiating = true;
- var result = mapType(mappedTypeVariable, function (t) {
- if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) {
+ return mapType(mappedTypeVariable, function (t) {
+ if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
var replacementMapper = createReplacementMapper(typeVariable, t, mapper);
- return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
- isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
+ return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
instantiateAnonymousType(type, replacementMapper);
}
return t;
});
- type.instantiating = false;
- return result;
}
}
return instantiateAnonymousType(type, mapper);
}
+ function getModifiedReadonlyState(state, modifiers) {
+ return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
+ }
+ function instantiateMappedArrayType(arrayType, mappedType, mapper) {
+ var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
+ return elementType === errorType ? errorType :
+ createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
+ }
function instantiateMappedTupleType(tupleType, mappedType, mapper) {
var minLength = tupleType.target.minLength;
var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) {
@@ -40841,7 +41254,9 @@
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);
+ var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
+ return ts.contains(elementTypes, errorType) ? errorType :
+ createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames);
}
function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key]));
@@ -40907,6 +41322,7 @@
// We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
// with a combination of infinite generic types that perpetually generate new type identities. We stop
// the recursion here by yielding the error type.
+ error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
return errorType;
}
instantiationDepth++;
@@ -40958,7 +41374,17 @@
return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
}
if (flags & 33554432 /* Substitution */) {
- return instantiateType(type.typeVariable, mapper);
+ var maybeVariable = instantiateType(type.typeVariable, mapper);
+ if (maybeVariable.flags & 8650752 /* TypeVariable */) {
+ return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
+ }
+ else {
+ var sub = instantiateType(type.substitute, mapper);
+ if (sub.flags & 3 /* AnyOrUnknown */ || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
+ return maybeVariable;
+ }
+ return sub;
+ }
}
return type;
}
@@ -40967,8 +41393,20 @@
type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
}
function getRestrictiveInstantiation(type) {
- return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
- type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper));
+ if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
+ return type;
+ }
+ if (type.restrictiveInstantiation) {
+ return type.restrictiveInstantiation;
+ }
+ type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
+ // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
+ // which is redundant - we'll produce new type identities, but all type params have already been mapped.
+ // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
+ // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
+ // are constrained to `unknown` and produce tons of false positives/negatives!
+ type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
+ return type.restrictiveInstantiation;
}
function instantiateIndexInfo(info, mapper) {
return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
@@ -41167,7 +41605,7 @@
var resultObj = {};
checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj);
var diagnostic = resultObj.error;
- addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
return true;
}
}
@@ -41202,7 +41640,7 @@
checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj);
if (resultObj.error) {
if (target.symbol && ts.length(target.symbol.declarations)) {
- addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
+ ts.addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
}
return true;
}
@@ -41249,13 +41687,13 @@
undefined;
if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
issuedElaboration = true;
- addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
+ ts.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))) {
var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
- addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
+ ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
}
}
}
@@ -41326,7 +41764,7 @@
// child is of the type of the expression
return { errorNode: child, innerExpression: child.expression, nameType: nameType };
case 11 /* JsxText */:
- if (child.containsOnlyWhiteSpaces) {
+ if (child.containsOnlyTriviaWhiteSpaces) {
break; // Whitespace only jsx text isn't real jsx text
}
// child is a string
@@ -41349,7 +41787,7 @@
var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
var childrenNameType = getLiteralType(childrenPropName);
var childrenTargetType = getIndexedAccessType(target, childrenNameType);
- var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyWhiteSpaces; });
+ var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
if (!ts.length(validChildren)) {
return result;
}
@@ -41437,7 +41875,7 @@
return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation);
}
// recreate a tuple from the elements, if possible
- var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true);
+ var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
if (isTupleLikeType(tupleizedType)) {
return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation);
}
@@ -41503,6 +41941,14 @@
/*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */;
}
/**
+ * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
+ */
+ function isAnySignature(s) {
+ return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
+ s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
+ isTypeAny(getReturnTypeOfSignature(s));
+ }
+ /**
* See signatureRelatedTo, compareSignaturesIdentical
*/
function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) {
@@ -41510,13 +41956,16 @@
if (source === target) {
return -1 /* True */;
}
+ if (isAnySignature(target)) {
+ return -1 /* True */;
+ }
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);
+ source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
}
var sourceCount = getParameterCount(source);
var sourceRestType = getNonArrayRestType(source);
@@ -41587,7 +42036,7 @@
if (targetTypePredicate) {
var sourceTypePredicate = getTypePredicateOfSignature(source);
if (sourceTypePredicate) {
- result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217
+ result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
}
else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
if (reportErrors) {
@@ -41606,7 +42055,7 @@
}
return result;
}
- function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) {
+ function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
if (source.kind !== target.kind) {
if (reportErrors) {
errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
@@ -41615,12 +42064,9 @@
return 0 /* False */;
}
if (source.kind === 1 /* Identifier */) {
- var targetPredicate = target;
- var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0);
- var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0);
- if (sourceIndex !== targetIndex) {
+ if (source.parameterIndex !== target.parameterIndex) {
if (reportErrors) {
- errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName);
+ errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
}
return 0 /* False */;
@@ -41821,7 +42267,7 @@
}
var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
if (relatedInfo) {
- addRelatedInfo.apply(void 0, [diag].concat(relatedInfo));
+ ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInfo));
}
if (errorOutputContainer) {
errorOutputContainer.error = diag;
@@ -42428,8 +42874,8 @@
if (source.root.isDistributive === target.root.isDistributive) {
if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
- if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
- if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
+ if (result_3 &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) {
+ if (result_3 &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) {
return result_3;
}
}
@@ -42444,6 +42890,7 @@
}
var result;
var originalErrorInfo;
+ var varianceCheckFailed = false;
var saveErrorInfo = errorInfo;
// We limit alias variance probing to only object and conditional types since their alias behavior
// is more predictable than other, interned types, which may or may not have an alias depending on
@@ -42452,11 +42899,10 @@
source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
!(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
var variances = getAliasVariances(source.aliasSymbol);
- if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) {
- return result;
+ var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances);
+ if (varianceResult !== undefined) {
+ return varianceResult;
}
- originalErrorInfo = errorInfo;
- errorInfo = saveErrorInfo;
}
if (target.flags & 262144 /* TypeParameter */) {
// A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q].
@@ -42513,9 +42959,18 @@
template.indexType === getTypeParameterFromMappedType(target)) {
return -1 /* True */;
}
+ if (!isGenericMappedType(source)) {
+ var targetConstraint = getConstraintTypeFromMappedType(target);
+ var sourceKeys_1 = getIndexType(source);
+ var hasOptionalUnionKeys = modifiers & 4 /* IncludeOptional */ && targetConstraint.flags & 1048576 /* Union */;
+ var filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, function (t) { return !!isRelatedTo(t, sourceKeys_1); }) : undefined;
// A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X.
- if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) {
- var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target));
+ // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X.
+ if (hasOptionalUnionKeys
+ ? !(filteredByApplicability.flags & 131072 /* Never */)
+ : isRelatedTo(targetConstraint, sourceKeys_1)) {
+ var indexingType = hasOptionalUnionKeys ? filteredByApplicability : getTypeParameterFromMappedType(target);
+ var indexedAccessType = getIndexedAccessType(source, indexingType);
var templateType = getTemplateTypeFromMappedType(target);
if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
return result;
@@ -42525,6 +42980,7 @@
errorInfo = saveErrorInfo;
}
}
+ }
if (source.flags & 8650752 /* TypeVariable */) {
if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
// A type S[K] is related to a type T[J] if S is related to T and K is related to J.
@@ -42568,8 +43024,8 @@
// and Y1 is related to Y2.
if (isTypeIdenticalTo(source.extendsType, target.extendsType) &&
(isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
- if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) {
- result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
+ if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) {
+ result &= isRelatedTo(source.falseType, target.falseType, reportErrors);
}
if (result) {
errorInfo = saveErrorInfo;
@@ -42618,36 +43074,19 @@
// type references (which are intended by be compared structurally). Obtain the variance
// information for the type parameters and relate the type arguments accordingly.
var variances = getVariances(source.target);
- if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) {
- return result;
- }
- // The type arguments did not relate appropriately, but it may be because we have no variance
- // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
- // arguments). It might also be the case that the target type has a 'void' type argument for
- // a covariant type parameter that is only used in return positions within the generic type
- // (in which case any type argument is permitted on the source side). In those cases we proceed
- // with a structural comparison. Otherwise, we know for certain the instantiations aren't
- // related and we can return here.
- if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) {
- // In some cases generic types that are covariant in regular type checking mode become
- // invariant in --strictFunctionTypes mode because one or more type parameters are used in
- // both co- and contravariant positions. In order to make it easier to diagnose *why* such
- // types are invariant, if any of the type parameters are invariant we reset the reported
- // errors and instead force a structural comparison (which will include elaborations that
- // reveal the reason).
- if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) {
- return 0 /* False */;
- }
- // We remember the original error information so we can restore it in case the structural
- // comparison unexpectedly succeeds. This can happen when the structural comparison result
- // is a Ternary.Maybe for example caused by the recursion depth limiter.
- originalErrorInfo = errorInfo;
- errorInfo = saveErrorInfo;
+ var varianceResult = relateVariances(source.typeArguments, target.typeArguments, variances);
+ if (varianceResult !== undefined) {
+ return varianceResult;
}
}
- else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) {
+ else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
}
+ // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
+ // and not `{} <- fresh({}) <- {[idx: string]: any}`
+ else if (relation === subtypeRelation && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
+ return 0 /* False */;
+ }
// Even if relationship doesn't hold for unions, intersections, or generic type references,
// it may hold in a structural comparison.
// In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
@@ -42669,17 +43108,57 @@
}
}
}
- if (result) {
- if (!originalErrorInfo) {
- errorInfo = saveErrorInfo;
+ if (varianceCheckFailed && result) {
+ errorInfo = originalErrorInfo || errorInfo || saveErrorInfo; // Use variance error (there is no structural one) and return false
+ }
+ else if (result) {
return result;
}
- errorInfo = originalErrorInfo;
}
}
+ return 0 /* False */;
+ function isNonGeneric(type) {
+ // If we're already in identity relationship checking, we should use `isRelatedTo`
+ // to catch the `Maybe` from an excessively deep type (which we then assume means
+ // that the type could possibly contain a generic)
+ if (relation === identityRelation) {
+ return isRelatedTo(type, getPermissiveInstantiation(type)) === -1 /* True */;
+ }
+ return isTypeIdenticalTo(type, getPermissiveInstantiation(type));
+ }
+ function relateVariances(sourceTypeArguments, targetTypeArguments, variances) {
+ if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors)) {
+ return result;
}
+ var allowStructuralFallback = (targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances)) || isNonGeneric(source) || isNonGeneric(target);
+ varianceCheckFailed = !allowStructuralFallback;
+ // The type arguments did not relate appropriately, but it may be because we have no variance
+ // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
+ // arguments). It might also be the case that the target type has a 'void' type argument for
+ // a covariant type parameter that is only used in return positions within the generic type
+ // (in which case any type argument is permitted on the source side). In those cases we proceed
+ // with a structural comparison. Otherwise, we know for certain the instantiations aren't
+ // related and we can return here.
+ if (variances !== ts.emptyArray && !allowStructuralFallback) {
+ // In some cases generic types that are covariant in regular type checking mode become
+ // invariant in --strictFunctionTypes mode because one or more type parameters are used in
+ // both co- and contravariant positions. In order to make it easier to diagnose *why* such
+ // types are invariant, if any of the type parameters are invariant we reset the reported
+ // errors and instead force a structural comparison (which will include elaborations that
+ // reveal the reason).
+ // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
+ // we can return `False` early here to skip calculating the structural error message we don't need.
+ if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) {
return 0 /* False */;
}
+ // We remember the original error information so we can restore it in case the structural
+ // comparison unexpectedly succeeds. This can happen when the structural comparison result
+ // is a Ternary.Maybe for example caused by the recursion depth limiter.
+ originalErrorInfo = errorInfo;
+ errorInfo = saveErrorInfo;
+ }
+ }
+ }
// A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
// related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
// that S and T are contra-variant whereas X and Y are co-variant.
@@ -43158,20 +43637,17 @@
return variances;
}
function getVariances(type) {
- if (!strictFunctionTypes) {
- return ts.emptyArray;
- }
- if (type === globalArrayType || type === globalReadonlyArrayType) {
- // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters)
+ // Arrays and tuples are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters)
+ if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
return ts.emptyArray;
}
return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
}
// Return true if the given type reference has a 'void' type argument for a covariant type parameter.
// See comment at call in recursiveTypeRelatedTo for when this case matters.
- function hasCovariantVoidArgument(type, variances) {
+ function hasCovariantVoidArgument(typeArguments, variances) {
for (var i = 0; i < variances.length; i++) {
- if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) {
+ if (variances[i] === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
return true;
}
}
@@ -43400,8 +43876,8 @@
}
function literalTypesWithSameBaseType(types) {
var commonBaseType;
- for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
- var t = types_8[_i];
+ for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
+ var t = types_9[_i];
var baseType = getBaseTypeOfLiteralType(t);
if (!commonBaseType) {
commonBaseType = baseType;
@@ -43434,7 +43910,7 @@
return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
}
function isArrayType(type) {
- return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType;
+ return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
}
function isReadonlyArrayType(type) {
return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
@@ -43445,8 +43921,7 @@
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<any>
- return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) ||
- !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
+ return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
}
function isEmptyArrayLiteralType(type) {
var elementType = isArrayType(type) ? type.typeArguments[0] : undefined;
@@ -43531,8 +44006,8 @@
}
function getFalsyFlagsOfTypes(types) {
var result = 0;
- for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
- var t = types_9[_i];
+ for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
+ var t = types_10[_i];
result |= getFalsyFlags(t);
}
return result;
@@ -43646,7 +44121,7 @@
var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
regularNew.flags = resolved.flags;
- regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */);
+ regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
type.regularType = regularNew;
return regularNew;
}
@@ -43725,14 +44200,14 @@
var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
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
+ result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening
return result;
}
function getWidenedType(type) {
return getWidenedTypeWithContext(type, /*context*/ undefined);
}
function getWidenedTypeWithContext(type, context) {
- if (type.flags & 402653184 /* RequiresWidening */) {
+ if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) {
if (type.flags & 98304 /* Nullable */) {
return anyType;
}
@@ -43769,7 +44244,7 @@
*/
function reportWideningErrorsInType(type) {
var errorReported = false;
- if (type.flags & 134217728 /* ContainsWideningType */) {
+ if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) {
if (type.flags & 1048576 /* Union */) {
if (ts.some(type.types, isEmptyObjectType)) {
errorReported = true;
@@ -43795,7 +44270,7 @@
for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
var p = _e[_d];
var t = getTypeOfSymbol(p);
- if (t.flags & 134217728 /* ContainsWideningType */) {
+ if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) {
if (!reportWideningErrorsInType(t)) {
error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
}
@@ -43841,7 +44316,7 @@
return;
}
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
return;
case 239 /* FunctionDeclaration */:
@@ -43868,14 +44343,14 @@
errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
}
function reportErrorsFromWidening(declaration, type) {
- if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) {
+ if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) {
// Report implicit any error within type if possible, otherwise report error on declaration
if (!reportWideningErrorsInType(type)) {
reportImplicitAny(declaration, type);
}
}
}
- function forEachMatchingParameterType(source, target, callback) {
+ function applyToParameterTypes(source, target, callback) {
var sourceCount = getParameterCount(source);
var targetCount = getParameterCount(target);
var sourceRestType = getEffectiveRestType(source);
@@ -43896,25 +44371,55 @@
callback(getRestTypeAtPosition(source, paramCount), targetRestType);
}
}
- function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) {
- var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo);
- var context = mapper;
- context.typeParameters = typeParameters;
- context.signature = signature;
- context.inferences = inferences;
- context.flags = flags;
- context.compareTypes = compareTypes || compareTypesAssignable;
+ function applyToReturnTypes(source, target, callback) {
+ var sourceTypePredicate = getTypePredicateOfSignature(source);
+ var targetTypePredicate = getTypePredicateOfSignature(target);
+ if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind &&
+ (sourceTypePredicate.kind === 0 /* This */ || sourceTypePredicate.parameterIndex === targetTypePredicate.parameterIndex)) {
+ callback(sourceTypePredicate.type, targetTypePredicate.type);
+ }
+ else {
+ callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
+ }
+ }
+ function createInferenceContext(typeParameters, signature, flags, compareTypes) {
+ return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
+ }
+ function cloneInferenceContext(context, extraFlags) {
+ if (extraFlags === void 0) { extraFlags = 0; }
+ return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
+ }
+ function cloneInferredPartOfContext(context) {
+ var inferences = ts.filter(context.inferences, hasInferenceCandidates);
+ return inferences.length ?
+ createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
+ undefined;
+ }
+ function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
+ var context = {
+ inferences: inferences,
+ signature: signature,
+ flags: flags,
+ compareTypes: compareTypes,
+ mapper: function (t) { return mapToInferredType(context, t, /*fix*/ true); },
+ nonFixingMapper: function (t) { return mapToInferredType(context, t, /*fix*/ false); },
+ };
return context;
- function mapper(t) {
+ }
+ function mapToInferredType(context, t, fix) {
+ var inferences = context.inferences;
for (var i = 0; i < inferences.length; i++) {
- if (t === inferences[i].typeParameter) {
- inferences[i].isFixed = true;
+ var inference = inferences[i];
+ if (t === inference.typeParameter) {
+ if (fix && !inference.isFixed) {
+ inference.isFixed = true;
+ inference.inferredType = undefined;
+ }
return getInferredType(context, i);
}
}
return t;
}
- }
function createInferenceInfo(typeParameter) {
return {
typeParameter: typeParameter,
@@ -43937,6 +44442,9 @@
isFixed: inference.isFixed
};
}
+ function getMapperFromContext(context) {
+ return context && context.mapper;
+ }
// Return true if the given type could possibly reference a type parameter for which
// we perform type inference (i.e. a type parameter of a generic function). We cache
// results for union and intersection types for performance reasons.
@@ -43993,31 +44501,21 @@
return type;
}
function createReverseMappedType(source, target, constraint) {
- var properties = getPropertiesOfType(source);
- if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) {
- return undefined;
- }
// If any property contains context sensitive functions that have been skipped, the source type
// is incomplete and we can't infer a meaningful input type.
- for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
- var prop = properties_3[_i];
- if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) {
+ if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || getPropertiesOfType(source).length === 0 && !getIndexInfoOfType(source, 0 /* String */)) {
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, constraint));
- }
- if (isReadonlyArrayType(source)) {
- return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint));
+ return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint), isReadonlyArrayType(source));
}
if (isTupleType(source)) {
var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); });
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);
+ return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, 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.
@@ -44038,16 +44536,16 @@
return getTypeFromInference(inference);
}
function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
- var properties, _i, properties_4, targetProp, sourceProp, targetType, sourceType;
+ var properties, _i, properties_3, targetProp, sourceProp, targetType, sourceType;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target);
- _i = 0, properties_4 = properties;
+ _i = 0, properties_3 = properties;
_a.label = 1;
case 1:
- if (!(_i < properties_4.length)) return [3 /*break*/, 6];
- targetProp = properties_4[_i];
+ if (!(_i < properties_3.length)) return [3 /*break*/, 6];
+ targetProp = properties_3[_i];
if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 5];
sourceProp = getPropertyOfType(source, targetProp.escapedName);
if (!!sourceProp) return [3 /*break*/, 3];
@@ -44091,11 +44589,11 @@
inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
emptyObjectType;
}
- function inferTypes(inferences, originalSource, originalTarget, priority) {
+ function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
if (priority === void 0) { priority = 0; }
+ if (contravariant === void 0) { contravariant = false; }
var symbolStack;
var visited;
- var contravariant = false;
var bivariant = false;
var propagationType;
var allowComplexConstraintInference = true;
@@ -44171,7 +44669,7 @@
// not contain anyFunctionType when we come back to this argument for its second round
// of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
// when constructing types from type parameters that had no inference candidates).
- if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) {
+ if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) {
return;
}
var inference = getInferenceInfoForType(target);
@@ -44180,6 +44678,7 @@
if (inference.priority === undefined || priority < inference.priority) {
inference.candidates = undefined;
inference.contraCandidates = undefined;
+ inference.topLevel = true;
inference.priority = priority;
}
if (priority === inference.priority) {
@@ -44187,14 +44686,19 @@
// We make contravariant inferences only if we are in a pure contravariant position,
// i.e. only if we have not descended into a bivariant position.
if (contravariant && !bivariant) {
- inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate);
+ if (!ts.contains(inference.contraCandidates, candidate)) {
+ inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
+ inference.inferredType = undefined;
}
- else {
- inference.candidates = ts.appendIfUnique(inference.candidates, candidate);
+ }
+ else if (!ts.contains(inference.candidates, candidate)) {
+ inference.candidates = ts.append(inference.candidates, candidate);
+ inference.inferredType = undefined;
}
}
- if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) {
+ if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
inference.topLevel = false;
+ inference.inferredType = undefined;
}
}
return;
@@ -44218,6 +44722,9 @@
}
}
}
+ else if (target.flags & 33554432 /* Substitution */) {
+ inferFromTypes(source, target.typeVariable);
+ }
if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) {
// If source and target are references to the same generic type, infer from type arguments
var sourceTypes = source.typeArguments || ts.emptyArray;
@@ -44254,42 +44761,48 @@
else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) {
inferFromTypes(source.checkType, target.checkType);
inferFromTypes(source.extendsType, target.extendsType);
- inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
- inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
+ inferFromTypes(source.trueType, target.trueType);
+ inferFromTypes(source.falseType, target.falseType);
}
- else if (target.flags & 16777216 /* Conditional */) {
- inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]));
+ else if (target.flags & 16777216 /* Conditional */ && !contravariant) {
+ inferFromTypes(source, target.trueType);
+ inferFromTypes(source, target.falseType);
}
else if (target.flags & 3145728 /* UnionOrIntersection */) {
- var targetTypes = target.types;
+ // We infer from types that are not naked type variables first so that inferences we
+ // make from nested naked type variables and given slightly higher priority by virtue
+ // of being first in the candidates array.
var typeVariableCount = 0;
- var typeVariable = void 0;
- // First infer to each type in union or intersection that isn't a type variable
- for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) {
- var t = targetTypes_3[_d];
+ for (var _d = 0, _e = target.types; _d < _e.length; _d++) {
+ var t = _e[_d];
if (getInferenceInfoForType(t)) {
- typeVariable = t;
typeVariableCount++;
}
else {
inferFromTypes(source, t);
}
}
- // Next, if target containings a single naked type variable, make a secondary inference to that type
- // variable. This gives meaningful results for union types in co-variant positions and intersection
- // types in contra-variant positions (such as callback parameters).
- if (typeVariableCount === 1) {
+ // Inferences directly to naked type variables are given lower priority as they are
+ // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
+ // we want to infer string for T, not Promise<string> | string. For intersection types
+ // we only infer to single naked type variables.
+ if (target.flags & 1048576 /* Union */ ? typeVariableCount !== 0 : typeVariableCount === 1) {
var savePriority = priority;
priority |= 1 /* NakedTypeVariable */;
- inferFromTypes(source, typeVariable);
+ for (var _f = 0, _g = target.types; _f < _g.length; _f++) {
+ var t = _g[_f];
+ if (getInferenceInfoForType(t)) {
+ inferFromTypes(source, t);
+ }
+ }
priority = savePriority;
}
}
else if (source.flags & 1048576 /* Union */) {
// Source is a union or intersection type, infer from each constituent type
var sourceTypes = source.types;
- for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) {
- var sourceType = sourceTypes_3[_e];
+ for (var _h = 0, sourceTypes_3 = sourceTypes; _h < sourceTypes_3.length; _h++) {
+ var sourceType = sourceTypes_3[_h];
inferFromTypes(sourceType, target);
}
}
@@ -44305,7 +44818,7 @@
// that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
// here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
// (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
- // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just
+ // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
// remove this `allowComplexConstraintInference` flag.
allowComplexConstraintInference = false;
return inferFromTypes(apparentSource, target);
@@ -44367,12 +44880,12 @@
}
return undefined;
}
- function inferFromMappedTypeConstraint(source, target, constraintType) {
+ function inferToMappedType(source, target, constraintType) {
if (constraintType.flags & 1048576 /* Union */) {
var result = false;
for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
var type = _a[_i];
- result = inferFromMappedTypeConstraint(source, target, type) || result;
+ result = inferToMappedType(source, target, type) || result;
}
return result;
}
@@ -44394,12 +44907,22 @@
return true;
}
if (constraintType.flags & 262144 /* TypeParameter */) {
- // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type
- // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X.
+ // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
+ // parameter. First infer from 'keyof S' to K.
var savePriority = priority;
priority |= 4 /* MappedTypeConstraint */;
inferFromTypes(getIndexType(source), constraintType);
priority = savePriority;
+ // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
+ // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
+ // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
+ // Pick<T, K>.
+ var extendedConstraint = getConstraintOfType(constraintType);
+ if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
+ return true;
+ }
+ // If no inferences can be made to K's constraint, infer from a union of the property types
+ // in the source to the template type X.
var valueTypes = ts.compact([
getIndexTypeOfType(source, 0 /* String */),
getIndexTypeOfType(source, 1 /* Number */)
@@ -44418,7 +44941,7 @@
}
if (ts.getObjectFlags(target) & 32 /* Mapped */) {
var constraintType = getConstraintTypeFromMappedType(target);
- if (inferFromMappedTypeConstraint(source, target, constraintType)) {
+ if (inferToMappedType(source, target, constraintType)) {
return;
}
}
@@ -44431,11 +44954,11 @@
}
}
function inferFromProperties(source, target) {
- if (isTupleType(source)) {
+ if (isArrayType(source) || isTupleType(source)) {
if (isTupleType(target)) {
- var sourceLength = getLengthOfTupleType(source);
+ var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0;
var targetLength = getLengthOfTupleType(target);
- var sourceRestType = getRestTypeOfTupleType(source);
+ var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source);
var targetRestType = getRestTypeOfTupleType(target);
var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
for (var i = 0; i < fixedLength; i++) {
@@ -44458,8 +44981,8 @@
}
}
var properties = getPropertiesOfObjectType(target);
- for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
- var targetProp = properties_5[_i];
+ for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) {
+ var targetProp = properties_4[_i];
var sourceProp = getPropertyOfType(source, targetProp.escapedName);
if (sourceProp) {
inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
@@ -44472,7 +44995,7 @@
var sourceLen = sourceSignatures.length;
var targetLen = targetSignatures.length;
var len = sourceLen < targetLen ? sourceLen : targetLen;
- var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */);
+ var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */);
for (var i = 0; i < len; i++) {
inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters);
}
@@ -44483,17 +45006,10 @@
var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
// Once we descend into a bivariant signature we remain bivariant for all nested inferences
bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */;
- forEachMatchingParameterType(source, target, inferFromContravariantTypes);
+ applyToParameterTypes(source, target, inferFromContravariantTypes);
bivariant = saveBivariant;
}
- var sourceTypePredicate = getTypePredicateOfSignature(source);
- var targetTypePredicate = getTypePredicateOfSignature(target);
- if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) {
- inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type);
- }
- else {
- inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
- }
+ applyToReturnTypes(source, target, inferFromTypes);
}
function inferFromIndexTypes(source, target) {
var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
@@ -44516,8 +45032,8 @@
}
}
function typeIdenticalToSomeType(type, types) {
- for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
- var t = types_10[_i];
+ for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
+ var t = types_11[_i];
if (isTypeIdenticalTo(t, type)) {
return true;
}
@@ -44610,7 +45126,7 @@
if (defaultType) {
// Instantiate the default type. Any forward reference to a type
// parameter should be instantiated to the empty object type.
- inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
}
else {
inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
@@ -44623,7 +45139,7 @@
inference.inferredType = inferredType;
var constraint = getConstraintOfTypeParameter(inference.typeParameter);
if (constraint) {
- var instantiatedConstraint = instantiateType(constraint, context);
+ var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
inference.inferredType = inferredType = instantiatedConstraint;
}
@@ -44648,17 +45164,23 @@
case "console":
return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
case "$":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
case "describe":
case "suite":
case "it":
case "test":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha;
case "process":
case "require":
case "Buffer":
case "module":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
case "Map":
case "Set":
case "Promise":
@@ -44794,9 +45316,8 @@
}
return false;
}
- function hasNarrowableDeclaredType(expr) {
- var type = getDeclaredTypeOfReference(expr);
- return !!(type && type.flags & 1048576 /* Union */);
+ function isSyntheticThisPropertyAccess(expr) {
+ return ts.isAccessExpression(expr) && expr.expression.kind === 100 /* ThisKeyword */ && !!(expr.expression.flags & 8 /* Synthesized */);
}
function findDiscriminantProperties(sourceProperties, target) {
var result;
@@ -44873,8 +45394,8 @@
}
function getTypeFactsOfTypes(types) {
var result = 0 /* None */;
- for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
- var t = types_11[_i];
+ for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
+ var t = types_12[_i];
result |= getTypeFacts(t);
}
return result;
@@ -45154,7 +45675,7 @@
if (type.flags & 1048576 /* Union */) {
var types = type.types;
var filtered = ts.filter(types, f);
- return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly);
+ return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
}
return f(type) ? type : neverType;
}
@@ -45168,8 +45689,8 @@
var types = type.types;
var mappedType;
var mappedTypes;
- for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
- var current = types_12[_i];
+ for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
+ var current = types_13[_i];
var t = mapper(current);
if (t) {
if (!mappedType) {
@@ -45251,8 +45772,8 @@
}
function isEvolvingArrayTypeList(types) {
var hasEvolvingArrayType = false;
- for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
- var t = types_13[_i];
+ for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
+ var t = types_14[_i];
if (!(t.flags & 131072 /* Never */)) {
if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
return false;
@@ -45750,6 +46271,15 @@
assumeTrue = !assumeTrue;
}
var valueType = getTypeOfExpression(value);
+ if ((type.flags & 2 /* Unknown */) && (operator === 35 /* EqualsEqualsEqualsToken */) && assumeTrue) {
+ if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
+ return valueType;
+ }
+ if (valueType.flags & 524288 /* Object */) {
+ return nonPrimitiveType;
+ }
+ return type;
+ }
if (valueType.flags & 98304 /* Nullable */) {
if (!strictNullChecks) {
return type;
@@ -45779,9 +46309,9 @@
// We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands
var target = getReferenceCandidate(typeOfExpr.expression);
if (!isMatchingReference(reference, target)) {
- // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a
- // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type.
- if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) {
+ // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the
+ // narrowed type of 'y' to its declared type.
+ if (containsMatchingReference(reference, target)) {
return declaredType;
}
return type;
@@ -45822,13 +46352,37 @@
}
}
function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
- // We only narrow if all case expressions specify values with unit types
+ // We only narrow if all case expressions specify
+ // values with unit types, except for the case where
+ // `type` is unknown. In this instance we map object
+ // types to the nonPrimitive type and narrow with that.
var switchTypes = getSwitchClauseTypes(switchStatement);
if (!switchTypes.length) {
return type;
}
var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
+ if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
+ var groundClauseTypes = void 0;
+ for (var i = 0; i < clauseTypes.length; i += 1) {
+ var t = clauseTypes[i];
+ if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
+ if (groundClauseTypes !== undefined) {
+ groundClauseTypes.push(t);
+ }
+ }
+ else if (t.flags & 524288 /* Object */) {
+ if (groundClauseTypes === undefined) {
+ groundClauseTypes = clauseTypes.slice(0, i);
+ }
+ groundClauseTypes.push(nonPrimitiveType);
+ }
+ else {
+ return type;
+ }
+ }
+ return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
+ }
var discriminantType = getUnionType(clauseTypes);
var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
@@ -45929,9 +46483,14 @@
function narrowTypeByInstanceof(type, expr, assumeTrue) {
var left = getReferenceCandidate(expr.left);
if (!isMatchingReference(reference, left)) {
- // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an
- // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type.
- if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) {
+ // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the
+ // narrowed type of 'y' to its declared type. We do this because preceding 'x.y'
+ // references might reference a different 'y' property. However, we make an exception
+ // for property accesses where x is a synthetic 'this' expression, indicating that we
+ // were called from isPropertyInitializedInConstructor. Without this exception,
+ // initializations of 'this' properties that occur before a 'this instanceof XXX'
+ // check would not be considered.
+ if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) {
return declaredType;
}
return type;
@@ -45998,7 +46557,7 @@
return type;
}
if (ts.isIdentifierTypePredicate(predicate)) {
- var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)];
+ var predicateArgument = callExpression.arguments[predicate.parameterIndex];
if (predicateArgument) {
if (isMatchingReference(reference, predicateArgument)) {
return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
@@ -46075,7 +46634,7 @@
return ts.findAncestor(node.parent, function (node) {
return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
node.kind === 245 /* ModuleBlock */ ||
- node.kind === 279 /* SourceFile */ ||
+ node.kind === 284 /* SourceFile */ ||
node.kind === 154 /* PropertyDeclaration */;
});
}
@@ -46196,7 +46755,7 @@
// 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 !== 279 /* SourceFile */) {
+ while (container.kind !== 284 /* SourceFile */) {
if (container.parent === declaration) {
if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
@@ -46302,6 +46861,7 @@
function checkNestedBlockScopedBinding(node, symbol) {
if (languageVersion >= 2 /* ES2015 */ ||
(symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
+ ts.isSourceFile(symbol.valueDeclaration) ||
symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) {
return;
}
@@ -46489,22 +47049,27 @@
if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
captureLexicalThis(node, container);
}
- var type = tryGetThisTypeAt(node, container);
- if (!type && noImplicitThis) {
+ var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
+ if (noImplicitThis) {
+ var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
+ if (type === globalThisType_1 && capturedByArrowFunction) {
+ error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
+ }
+ else if (!type) {
// With noImplicitThis, functions may not reference 'this' if it has type 'any'
- var diag = error(node, capturedByArrowFunction && container.kind === 279 /* 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);
+ var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
if (!ts.isSourceFile(container)) {
var outsideThis = tryGetThisTypeAt(container);
- if (outsideThis) {
- addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
+ if (outsideThis && outsideThis !== globalThisType_1) {
+ ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
+ }
}
}
}
return type || anyType;
}
- function tryGetThisTypeAt(node, container) {
+ function tryGetThisTypeAt(node, includeGlobalThis, container) {
+ if (includeGlobalThis === void 0) { includeGlobalThis = true; }
if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
var isInJS = ts.isInJSFile(node);
if (ts.isFunctionLike(container) &&
@@ -46549,6 +47114,16 @@
return getFlowTypeOfReference(node, type);
}
}
+ if (ts.isSourceFile(container)) {
+ // look up in the source file's locals or exports
+ if (container.commonJsModuleIndicator) {
+ var fileSymbol = getSymbolOfNode(container);
+ return fileSymbol && getTypeOfSymbol(fileSymbol);
+ }
+ else if (includeGlobalThis) {
+ return getTypeOfSymbol(globalThisSymbol);
+ }
+ }
}
function getClassNameFromPrototypeMethod(container) {
// Check if it's the RHS of a x.prototype.y = function [name]() { .... }
@@ -46604,7 +47179,7 @@
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 294 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -46618,7 +47193,7 @@
}
}
function isInConstructorArgumentInitializer(node, constructorDecl) {
- return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; });
+ return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 151 /* Parameter */ && n.parent === constructorDecl; });
}
function checkSuperExpression(node) {
var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node;
@@ -46843,7 +47418,7 @@
while (type) {
var thisType = getThisTypeFromContextualType(type);
if (thisType) {
- return instantiateType(thisType, getContextualMapper(containingLiteral));
+ return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
}
if (literal.parent.kind !== 275 /* PropertyAssignment */) {
break;
@@ -47138,7 +47713,15 @@
}
function getTypeOfPropertyOfContextualType(type, name) {
return mapType(type, function (t) {
- if (t.flags & 3670016 /* StructuredType */) {
+ if (isGenericMappedType(t)) {
+ var constraint = getConstraintTypeFromMappedType(t);
+ var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
+ var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
+ if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
+ return substituteIndexedMappedType(t, propertyNameType);
+ }
+ }
+ else if (t.flags & 3670016 /* StructuredType */) {
var prop = getPropertyOfType(t, name);
if (prop) {
return getTypeOfSymbol(prop);
@@ -47274,18 +47857,46 @@
// Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
// be "pushed" onto a node using the contextualType property.
function getApparentTypeOfContextualType(node) {
- var contextualType = getContextualType(node);
- contextualType = contextualType && mapType(contextualType, getApparentType);
- if (contextualType && contextualType.flags & 1048576 /* Union */) {
+ var contextualType = instantiateContextualType(getContextualType(node), node);
+ if (contextualType) {
+ var apparentType = mapType(contextualType, getApparentType, /*noReductions*/ true);
+ if (apparentType.flags & 1048576 /* Union */) {
if (ts.isObjectLiteralExpression(node)) {
- return discriminateContextualTypeByObjectMembers(node, contextualType);
+ return discriminateContextualTypeByObjectMembers(node, apparentType);
}
else if (ts.isJsxAttributes(node)) {
- return discriminateContextualTypeByJSXAttributes(node, contextualType);
+ return discriminateContextualTypeByJSXAttributes(node, apparentType);
+ }
+ }
+ return apparentType;
+ }
+ }
+ // If the given contextual type contains instantiable types and if a mapper representing
+ // return type inferences is available, instantiate those types using that mapper.
+ function instantiateContextualType(contextualType, node) {
+ if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) {
+ var inferenceContext = getInferenceContext(node);
+ if (inferenceContext && inferenceContext.returnMapper) {
+ return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
}
}
return contextualType;
}
+ // This function is similar to instantiateType, except that (a) it only instantiates types that
+ // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
+ // no reductions on instantiated union types.
+ function instantiateInstantiableTypes(type, mapper) {
+ if (type.flags & 63176704 /* Instantiable */) {
+ return instantiateType(type, mapper);
+ }
+ if (type.flags & 1048576 /* Union */) {
+ return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
+ }
+ if (type.flags & 2097152 /* Intersection */) {
+ return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
+ }
+ return type;
+ }
/**
* Woah! Do you really want to use this function?
*
@@ -47331,7 +47942,7 @@
return getContextualTypeForArgument(parent, node);
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- return getTypeFromTypeNode(parent.type);
+ return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type);
case 204 /* BinaryExpression */:
return getContextualTypeForBinaryOperand(node);
case 275 /* PropertyAssignment */:
@@ -47365,9 +47976,9 @@
}
return undefined;
}
- function getContextualMapper(node) {
- var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; });
- return ancestor ? ancestor.contextualMapper : identityMapper;
+ function getInferenceContext(node) {
+ var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
+ return ancestor && ancestor.inferenceContext;
}
function getContextualJsxElementAttributesType(node) {
if (ts.isJsxOpeningElement(node) && node.parent.contextualType) {
@@ -47548,8 +48159,8 @@
}
var signatureList;
var types = type.types;
- for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
- var current = types_14[_i];
+ for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
+ var current = types_15[_i];
var signature = getContextualCallSignature(current, node);
if (signature) {
if (!signatureList) {
@@ -47567,12 +48178,7 @@
}
}
// Result is union of signatures collected (return type is union of return types of this signature set)
- var result;
- if (signatureList) {
- result = cloneSignature(signatureList[0]);
- result.unionSignatures = signatureList;
- }
- return result;
+ return signatureList && createUnionSignature(signatureList[0], signatureList);
}
function checkSpreadExpression(node, checkMode) {
if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
@@ -47592,6 +48198,7 @@
var elementTypes = [];
var inDestructuringPattern = ts.isAssignmentTarget(node);
var contextualType = getApparentTypeOfContextualType(node);
+ var inConstContext = isConstContext(node);
for (var index = 0; index < elementCount; index++) {
var e = elements[index];
if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) {
@@ -47634,21 +48241,24 @@
type.pattern = node;
return type;
}
- else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) {
+ else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, inConstContext)) {
return tupleResult;
}
else if (forceTuple) {
return createTupleType(elementTypes, minLength, hasRestElement);
}
}
- return getArrayLiteralType(elementTypes, 2 /* Subtype */);
+ return createArrayType(elementTypes.length ?
+ getUnionType(elementTypes, 2 /* Subtype */) :
+ strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext);
}
- function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) {
+ function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) {
if (elementCount === void 0) { elementCount = elementTypes.length; }
+ if (readonly === void 0) { readonly = false; }
// Infer a tuple type when the contextual type is or contains a tuple-like type
- if (contextualType && forEachType(contextualType, isTupleLikeType)) {
+ if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) {
var minLength = elementCount - (hasRestElement ? 1 : 0);
- var pattern = contextualType.pattern;
+ var pattern = contextualType && 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 (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) {
@@ -47666,15 +48276,9 @@
}
}
}
- return createTupleType(elementTypes, minLength, hasRestElement);
+ return createTupleType(elementTypes, minLength, hasRestElement, readonly);
}
}
- function getArrayLiteralType(elementTypes, unionReduction) {
- if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
- return createArrayType(elementTypes.length ?
- getUnionType(elementTypes, unionReduction) :
- strictNullChecks ? implicitNeverType : undefinedWideningType);
- }
function isNumericName(name) {
switch (name.kind) {
case 149 /* ComputedPropertyName */:
@@ -47737,15 +48341,15 @@
}
return links.resolvedType;
}
- function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) {
+ function getObjectLiteralIndexInfo(node, offset, properties, kind) {
var propTypes = [];
for (var i = 0; i < properties.length; i++) {
- if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) {
+ if (kind === 0 /* String */ || isNumericName(node.properties[i + offset].name)) {
propTypes.push(getTypeOfSymbol(properties[i]));
}
}
var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
- return createIndexInfo(unionType, /*isReadonly*/ false);
+ return createIndexInfo(unionType, isConstContext(node));
}
function getImmediateAliasedSymbol(symbol) {
ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
@@ -47765,14 +48369,15 @@
var propertiesTable;
var propertiesArray = [];
var spread = emptyObjectType;
- var propagatedFlags = 0;
var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */);
+ var inConstContext = isConstContext(node);
+ var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
var enumTag = ts.getJSDocEnumTag(node);
var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
- var typeFlags = 0;
+ var objectFlags = freshObjectLiteralFlag;
var patternWithComputedProperties = false;
var hasComputedStringProperty = false;
var hasComputedNumberProperty = false;
@@ -47799,11 +48404,11 @@
checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
}
}
- typeFlags |= type.flags;
+ objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */;
var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
var prop = nameType ?
- createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), 2048 /* Late */) :
- createSymbol(4 /* Property */ | member.flags, member.escapedName);
+ createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 2048 /* Late */) :
+ createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
if (nameType) {
prop.nameType = nameType;
}
@@ -47841,19 +48446,18 @@
checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
}
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
propertiesArray = [];
propertiesTable = ts.createSymbolTable();
hasComputedStringProperty = false;
hasComputedNumberProperty = false;
- typeFlags = 0;
}
var type = checkExpression(memberDecl.expression);
if (!isValidSpreadType(type)) {
error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
return errorType;
}
- spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
offset = i + 1;
continue;
}
@@ -47900,17 +48504,16 @@
}
if (spread !== emptyObjectType) {
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
}
return spread;
}
return createObjectLiteralType();
function createObjectLiteralType() {
- var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined;
- var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined;
+ var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
+ var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
- result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */;
- result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag;
+ result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
if (isJSObjectLiteral) {
result.objectFlags |= 16384 /* JSLiteral */;
}
@@ -47920,7 +48523,6 @@
if (inDestructuringPattern) {
result.pattern = node;
}
- propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */;
return result;
}
}
@@ -47996,7 +48598,6 @@
var hasSpreadAnyType = false;
var typeToIntersect;
var explicitlySpecifyChildrenAttribute = false;
- var typeFlags = 0;
var objectFlags = 4096 /* JsxAttributes */;
var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
@@ -48004,7 +48605,7 @@
var member = attributeDecl.symbol;
if (ts.isJsxAttribute(attributeDecl)) {
var exprType = checkJsxAttribute(attributeDecl, checkMode);
- typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */;
+ objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */;
var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
attributeSymbol.declarations = member.declarations;
attributeSymbol.parent = member.parent;
@@ -48021,7 +48622,7 @@
else {
ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */);
if (attributesTable.size > 0) {
- spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
attributesTable = ts.createSymbolTable();
}
var exprType = checkExpressionCached(attributeDecl.expression, checkMode);
@@ -48029,7 +48630,7 @@
hasSpreadAnyType = true;
}
if (isValidSpreadType(exprType)) {
- spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
}
else {
typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
@@ -48038,7 +48639,7 @@
}
if (!hasSpreadAnyType) {
if (attributesTable.size > 0) {
- spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
}
}
// Handle children attribute
@@ -48066,7 +48667,7 @@
childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
var childPropMap = ts.createSymbolTable();
childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
- spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
}
}
if (hasSpreadAnyType) {
@@ -48084,8 +48685,7 @@
function createJsxAttributesType() {
objectFlags |= freshObjectLiteralFlag;
var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
- result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags;
- result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags;
+ result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
return result;
}
}
@@ -48096,7 +48696,7 @@
// In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
// because then type of children property will have constituent of string type.
if (child.kind === 11 /* JsxText */) {
- if (!child.containsOnlyWhiteSpaces) {
+ if (!child.containsOnlyTriviaWhiteSpaces) {
childrenTypes.push(stringType);
}
}
@@ -48167,7 +48767,7 @@
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 */);
+ var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
if (candidate) {
if (links) {
links.jsxNamespace = candidate;
@@ -48372,7 +48972,7 @@
// Mark local symbol as referenced here because it might not have been marked
// if jsx emit was not react as there wont be error being emitted
reactSym.isReferenced = 67108863 /* All */;
- // If react symbol is alias, mark it as refereced
+ // If react symbol is alias, mark it as referenced
if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) {
markAliasSymbolAsReferenced(reactSym);
}
@@ -48610,6 +49210,15 @@
if (isJSLiteralType(leftType)) {
return anyType;
}
+ if (leftType.symbol === globalThisSymbol) {
+ if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
+ error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
+ }
+ else if (noImplicitAny) {
+ error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
+ }
+ return anyType;
+ }
if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType);
}
@@ -48688,7 +49297,7 @@
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));
+ ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
}
}
function isInPropertyInitializer(node) {
@@ -48697,7 +49306,19 @@
case 154 /* PropertyDeclaration */:
return true;
case 275 /* PropertyAssignment */:
- // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`.
+ case 156 /* MethodDeclaration */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
+ case 277 /* SpreadAssignment */:
+ case 149 /* ComputedPropertyName */:
+ case 216 /* TemplateSpan */:
+ case 270 /* JsxExpression */:
+ case 267 /* JsxAttribute */:
+ case 268 /* JsxAttributes */:
+ case 269 /* JsxSpreadAttribute */:
+ case 262 /* JsxOpeningElement */:
+ case 211 /* ExpressionWithTypeArguments */:
+ case 273 /* HeritageClause */:
return false;
default:
return ts.isExpressionNode(node) ? false : "quit";
@@ -48765,7 +49386,7 @@
}
var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
if (relatedInfo) {
- addRelatedInfo(resultDiagnostic, relatedInfo);
+ ts.addRelatedInfo(resultDiagnostic, relatedInfo);
}
diagnostics.add(resultDiagnostic);
}
@@ -49164,38 +49785,34 @@
return undefined;
}
// 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) {
+ function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
- var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature;
- forEachMatchingParameterType(sourceSignature, signature, function (source, target) {
+ // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
+ // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
+ // for T but leave it possible to later infer '[any]' back to A.
+ var restType = getEffectiveRestType(contextualSignature);
+ var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
+ var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
+ applyToParameterTypes(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, source, target);
});
- if (!contextualMapper) {
- inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */);
+ if (!inferenceContext) {
+ applyToReturnTypes(contextualSignature, signature, function (source, target) {
+ inferTypes(context.inferences, source, target, 8 /* ReturnType */);
+ });
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
}
- function inferJsxTypeArguments(node, signature, excludeArgument, context) {
+ function inferJsxTypeArguments(node, signature, checkMode, context) {
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context);
+ var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
inferTypes(context.inferences, checkAttrType, paramType);
return getInferredTypes(context);
}
- function inferTypeArguments(node, signature, args, excludeArgument, context) {
- // Clear out all the inference results from the last time inferTypeArguments was called on this context
- for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) {
- var inference = _a[_i];
- // As an optimization, we don't have to clear (and later recompute) inferred types
- // for type parameters that have already been fixed on the previous call to inferTypeArguments.
- // It would be just as correct to reset all of them. But then we'd be repeating the same work
- // for the type parameters that were fixed, namely the work done by getInferredType.
- if (!inference.isFixed) {
- inference.inferredType = undefined;
- }
- }
+ function inferTypeArguments(node, signature, args, checkMode, context) {
if (ts.isJsxOpeningLikeElement(node)) {
- return inferJsxTypeArguments(node, signature, excludeArgument, context);
+ return inferJsxTypeArguments(node, signature, checkMode, context);
}
// If a contextual type is available, infer from that type to the return type of the call expression. For
// example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
@@ -49204,10 +49821,11 @@
if (node.kind !== 152 /* Decorator */) {
var contextualType = getContextualType(node);
if (contextualType) {
- // We clone the contextual mapper to avoid disturbing a resolution in progress for an
+ // We clone the inference context to avoid disturbing a resolution in progress for an
// outer call expression. Effectively we just want a snapshot of whatever has been
// inferred for any outer call expression so far.
- var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node)));
+ var outerMapper = getMapperFromContext(cloneInferenceContext(getInferenceContext(node), 1 /* NoDefault */));
+ var instantiatedType = instantiateType(contextualType, outerMapper);
// If the contextual type is a generic function type with a single call signature, we
// instantiate the type with its own type parameters and type arguments. This ensures that
// the type parameters are not erased to type any during type inference such that they can
@@ -49222,6 +49840,9 @@
var inferenceTargetType = getReturnTypeOfSignature(signature);
// Inferences made from return types have lower priority than all other inferences.
inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */);
+ // Create a type mapper for instantiating generic contextual types using the inferences made
+ // from the return type.
+ context.returnMapper = getMapperFromContext(cloneInferredPartOfContext(context));
}
}
var thisType = getThisTypeOfSignature(signature);
@@ -49236,10 +49857,7 @@
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- // For context sensitive arguments we pass the identityMapper, which is a signal to treat all
- // context sensitive function expressions as wildcards
- var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
- var argType = checkExpressionWithContextualType(arg, paramType, mapper);
+ var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
inferTypes(context.inferences, argType, paramType);
}
}
@@ -49263,7 +49881,7 @@
// and the argument are ...x forms.
return arg.kind === 215 /* SyntheticExpression */ ?
createArrayType(arg.type) :
- getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context));
+ getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
}
}
var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType;
@@ -49271,7 +49889,7 @@
var types = [];
var spreadIndex = -1;
for (var i = index; i < argCount; i++) {
- var argType = checkExpressionWithContextualType(args[i], contextualType, context);
+ var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
if (spreadIndex < 0 && isSpreadArgument(args[i])) {
spreadIndex = i - index;
}
@@ -49321,19 +49939,18 @@
* @param node a JSX opening-like element we are trying to figure its call signature
* @param signature a candidate signature we are trying whether it is a call signature
* @param relation a relationship to check parameter and argument type
- * @param excludeArgument
*/
- function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors) {
// Stateless function components can have maximum of three arguments: "props", "context", and "updater".
// However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
// can be specified by users through attributes property.
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined);
+ var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes);
}
- function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignature(node, args, signature, relation, checkMode, reportErrors) {
if (ts.isJsxOpeningLikeElement(node)) {
- return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors);
+ return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors);
}
var thisType = getThisTypeOfSignature(signature);
if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) {
@@ -49355,11 +49972,11 @@
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
- // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter),
+ var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
+ // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
// 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;
+ var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
return false;
}
@@ -49516,25 +50133,41 @@
if (argCount <= max && hasSpreadArgument) {
argCount--;
}
+ var spanArray;
var related;
+ var error = hasRestParameter || hasSpreadArgument ? 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 : ts.Diagnostics.Expected_0_arguments_but_got_1;
if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
if (paramDecl) {
related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined);
}
}
- 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;
- var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount);
- return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1;
- }
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);
}
- var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount);
- return related ? addRelatedInfo(diagnostic, related) : diagnostic;
+ if (!hasSpreadArgument && argCount < min) {
+ var diagnostic_1 = ts.createDiagnosticForNode(node, error, paramRange, argCount);
+ return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
+ }
+ if (hasRestParameter || hasSpreadArgument) {
+ spanArray = ts.createNodeArray(args);
+ if (hasSpreadArgument && argCount) {
+ var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
+ spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
+ }
+ }
+ else {
+ spanArray = ts.createNodeArray(args.slice(max));
+ }
+ spanArray.pos = ts.first(spanArray).pos;
+ spanArray.end = ts.last(spanArray).end;
+ if (spanArray.end === spanArray.pos) {
+ spanArray.end++;
+ }
+ var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
+ return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
}
function getTypeArgumentArityError(node, signatures, typeArguments) {
var argCount = typeArguments.length;
@@ -49564,7 +50197,7 @@
}
return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
}
- function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) {
+ function resolveCall(node, signatures, candidatesOutArray, checkMode, fallbackError) {
var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */;
var isDecorator = node.kind === 152 /* Decorator */;
var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
@@ -49600,7 +50233,7 @@
// For a decorator, no arguments are susceptible to contextual typing due to the fact
// decorators are applied to a declaration by the emitter, and not to an expression.
var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
- var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined;
+ var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
// The following variables are captured and modified by calls to chooseOverload.
// If overload resolution or type argument inference fails, we want to report the
// best error possible. The best error is one which says that an argument was not
@@ -49628,7 +50261,7 @@
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 = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
+ var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 191 /* 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
@@ -49654,12 +50287,7 @@
// skip the checkApplicableSignature check.
if (reportErrors) {
if (candidateForArgumentError) {
- // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...]
- // The importance of excludeArgument is to prevent us from typing function expression parameters
- // in arguments too early. If possible, we'd like to only type them once we know the correct
- // overload. However, this matters for the case where the call is correct. When the call is
- // 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);
+ checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, 0 /* Normal */, /*reportErrors*/ true);
}
else if (candidateForArgumentArityError) {
diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
@@ -49691,7 +50319,7 @@
if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
return undefined;
}
- if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false)) {
candidateForArgumentError = candidate;
return undefined;
}
@@ -49715,9 +50343,10 @@
}
else {
inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
+ typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
+ argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
}
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// 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 (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -49728,21 +50357,21 @@
else {
checkCandidate = candidate;
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
}
continue;
}
- if (excludeArgument) {
+ if (argCheckMode) {
// If one or more context sensitive arguments were excluded, we start including
// them now (and keeping do so for any subsequent candidates) and perform a second
// round of type inference and applicability checking for this particular candidate.
- excludeArgument = undefined;
+ argCheckMode = 0 /* Normal */;
if (inferenceContext) {
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// 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 (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -49750,7 +50379,7 @@
continue;
}
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
@@ -49764,20 +50393,6 @@
return undefined;
}
}
- function getExcludeArgument(args) {
- var excludeArgument;
- // We do not need to call `getEffectiveArgumentCount` here as it only
- // applies when calculating the number of arguments for a decorator.
- for (var i = 0; i < args.length; i++) {
- if (isContextSensitive(args[i])) {
- if (!excludeArgument) {
- excludeArgument = new Array(args.length);
- }
- excludeArgument[i] = true;
- }
- }
- return excludeArgument;
- }
// 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) {
@@ -49866,7 +50481,7 @@
}
function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext);
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
return createSignatureInstantiation(candidate, typeArgumentTypes);
}
function getLongestCandidateIndex(candidates, argsCount) {
@@ -49885,7 +50500,7 @@
}
return maxParamsIndex;
}
- function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveCallExpression(node, candidatesOutArray, checkMode) {
if (node.expression.kind === 98 /* SuperKeyword */) {
var superType = checkSuperExpression(node.expression);
if (isTypeAny(superType)) {
@@ -49901,7 +50516,7 @@
var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
if (baseTypeNode) {
var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
- return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, baseConstructors, candidatesOutArray, checkMode);
}
}
return resolveUntypedCall(node);
@@ -49951,12 +50566,31 @@
}
return resolveErrorCall(node);
}
+ // When a call to a generic function is an argument to an outer call to a generic function for which
+ // inference is in process, we have a choice to make. If the inner call relies on inferences made from
+ // its contextual type to its return type, deferring the inner call processing allows the best possible
+ // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
+ // the inner call, the inner call should be processed early. There's no sure way to know which choice is
+ // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
+ // If no type arguments are specified in the inner call and at least one call signature is generic and
+ // returns a function type, we choose to defer processing. This narrowly permits function composition
+ // operators to flow inferences through return types, but otherwise processes calls right away. We
+ // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
+ // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
+ // from which we never make inferences).
+ if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
+ skippedGenericFunction(node, checkMode);
+ return resolvingSignature;
+ }
// If the function is explicitly marked with `@class`, then it must be constructed.
if (callSignatures.some(function (sig) { return ts.isInJSFile(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);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
+ }
+ function isGenericFunctionReturningFunction(signature) {
+ return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
}
/**
* TS 1.0 spec: 4.12
@@ -49968,7 +50602,7 @@
return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
!numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
}
- function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveNewExpression(node, candidatesOutArray, checkMode) {
if (node.arguments && languageVersion < 1 /* ES5 */) {
var spreadIndex = getSpreadArgumentIndex(node.arguments);
if (spreadIndex >= 0) {
@@ -50016,7 +50650,7 @@
error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
return resolveErrorCall(node);
}
- return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, constructSignatures, candidatesOutArray, checkMode);
}
// 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
@@ -50024,7 +50658,7 @@
// 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, isForSignatureHelp);
+ var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode);
if (!noImplicitAny) {
if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
@@ -50046,13 +50680,12 @@
var firstBase = baseTypes[0];
if (firstBase.flags & 2097152 /* Intersection */) {
var types = firstBase.types;
- var mixinCount = ts.countWhere(types, isMixinConstructorType);
+ var mixinFlags = findMixins(types);
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 (!mixinFlags[i]) {
if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
if (intersectionMember.symbol === target) {
return true;
@@ -50062,6 +50695,7 @@
}
}
}
+ i++;
}
return false;
}
@@ -50105,7 +50739,7 @@
var diagnostic = 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, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
+ invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
}
function invocationErrorRecovery(apparentType, kind, diagnostic) {
if (!apparentType.symbol) {
@@ -50118,10 +50752,10 @@
var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
if (!sigs || !sigs.length)
return;
- 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));
+ 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, isForSignatureHelp) {
+ function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
var tagType = checkExpression(node.tag);
var apparentType = getApparentType(tagType);
if (apparentType === errorType) {
@@ -50137,7 +50771,7 @@
invocationError(node, apparentType, 0 /* Call */);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
}
/**
* Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
@@ -50162,7 +50796,7 @@
/**
* Resolves a decorator as if it were a call expression.
*/
- function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveDecorator(node, candidatesOutArray, checkMode) {
var funcType = checkExpression(node.expression);
var apparentType = getApparentType(funcType);
if (apparentType === errorType) {
@@ -50187,7 +50821,7 @@
invocationErrorRecovery(apparentType, 0 /* Call */, diag);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode, headMessage);
}
function createSignatureForJSXIntrinsic(node, result) {
var namespace = getJsxNamespaceAt(node);
@@ -50206,11 +50840,11 @@
/*hasRestparameter*/ false,
/*hasLiteralTypes*/ false);
}
- function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
var fakeSignature = createSignatureForJSXIntrinsic(node, result);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes);
+ checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
return fakeSignature;
}
var exprTypes = checkExpression(node.tagName);
@@ -50227,7 +50861,7 @@
error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
return resolveErrorCall(node);
}
- return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, signatures, candidatesOutArray, checkMode);
}
/**
* Sometimes, we have a decorator that could accept zero arguments,
@@ -50241,19 +50875,19 @@
signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
});
}
- function resolveSignature(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveSignature(node, candidatesOutArray, checkMode) {
switch (node.kind) {
case 191 /* CallExpression */:
- return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveCallExpression(node, candidatesOutArray, checkMode);
case 192 /* NewExpression */:
- return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveNewExpression(node, candidatesOutArray, checkMode);
case 193 /* TaggedTemplateExpression */:
- return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
case 152 /* Decorator */:
- return resolveDecorator(node, candidatesOutArray, isForSignatureHelp);
+ return resolveDecorator(node, candidatesOutArray, checkMode);
case 262 /* JsxOpeningElement */:
case 261 /* JsxSelfClosingElement */:
- return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp);
+ return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
}
throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
}
@@ -50264,8 +50898,7 @@
* 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, isForSignatureHelp) {
- if (isForSignatureHelp === void 0) { isForSignatureHelp = false; }
+ function getResolvedSignature(node, candidatesOutArray, checkMode) {
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,
@@ -50276,11 +50909,15 @@
return cached;
}
links.resolvedSignature = resolvingSignature;
- var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp);
+ var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
+ // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
+ // resolution should be deferred.
+ if (result !== resolvingSignature) {
// 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.
links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ }
return result;
}
/**
@@ -50356,10 +50993,15 @@
* @param node The call/new expression to be checked.
* @returns On success, the expression's signature's return type. On failure, anyType.
*/
- function checkCallExpression(node) {
+ function checkCallExpression(node, checkMode) {
if (!checkGrammarTypeArguments(node, node.typeArguments))
checkGrammarArguments(node.arguments);
- var signature = getResolvedSignature(node);
+ var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
+ if (signature === resolvingSignature) {
+ // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
+ // returns a function type. We defer checking and return nonInferrableType.
+ return nonInferrableType;
+ }
if (node.expression.kind === 98 /* SuperKeyword */) {
return voidType;
}
@@ -50459,7 +51101,7 @@
var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
anonymousSymbol.type = defaultContainingObject;
- synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0) : defaultContainingObject;
+ synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
}
else {
synthType.syntheticType = type;
@@ -50506,9 +51148,37 @@
function checkAssertion(node) {
return checkAssertionWorker(node, node.type, node.expression);
}
+ function isValidConstAssertionArgument(node) {
+ switch (node.kind) {
+ case 10 /* StringLiteral */:
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 8 /* NumericLiteral */:
+ case 9 /* BigIntLiteral */:
+ case 102 /* TrueKeyword */:
+ case 87 /* FalseKeyword */:
+ case 187 /* ArrayLiteralExpression */:
+ case 188 /* ObjectLiteralExpression */:
+ return true;
+ case 195 /* ParenthesizedExpression */:
+ return isValidConstAssertionArgument(node.expression);
+ case 202 /* PrefixUnaryExpression */:
+ var op = node.operator;
+ var arg = node.operand;
+ return op === 39 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
+ op === 38 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
+ }
+ return false;
+ }
function checkAssertionWorker(errNode, type, expression, checkMode) {
- var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode)));
+ var exprType = checkExpression(expression, checkMode);
+ if (ts.isConstTypeReference(type)) {
+ if (!isValidConstAssertionArgument(expression)) {
+ error(expression, ts.Diagnostics.A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal);
+ }
+ return getRegularTypeOfLiteralType(exprType);
+ }
checkSourceElement(type);
+ exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
var targetType = getTypeFromTypeNode(type);
if (produceDiagnostics && targetType !== errorType) {
var widenedType = getWidenedType(exprType);
@@ -50547,7 +51217,7 @@
}
}
function checkImportMetaProperty(node) {
- if (languageVersion < 6 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) {
+ if (languageVersion < 7 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) {
error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options);
}
var file = ts.getSourceFileOfNode(node);
@@ -50575,7 +51245,7 @@
if (isTupleType(restType)) {
var associatedNames = restType.target.associatedNames;
var index = pos - paramCount;
- return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index;
+ return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
}
return restParameter.escapedName;
}
@@ -50588,33 +51258,37 @@
return getTypeOfParameter(signature.parameters[pos]);
}
if (signature.hasRestParameter) {
+ // We want to return the value undefined for an out of bounds parameter position,
+ // so we need to check bounds here before calling getIndexedAccessType (which
+ // otherwise would return the type 'undefined').
var restType = getTypeOfSymbol(signature.parameters[paramCount]);
- if (isTupleType(restType)) {
- if (pos - paramCount < getLengthOfTupleType(restType)) {
- return restType.typeArguments[pos - paramCount];
- }
- return getRestTypeOfTupleType(restType);
+ var index = pos - paramCount;
+ if (!isTupleType(restType) || restType.target.hasRestElement || index < (restType.typeArguments || ts.emptyArray).length) {
+ return getIndexedAccessType(restType, getLiteralType(index));
}
- return getIndexTypeOfType(restType, 1 /* Number */);
}
return undefined;
}
function getRestTypeAtPosition(source, pos) {
var paramCount = getParameterCount(source);
var restType = getEffectiveRestType(source);
- if (restType && pos === paramCount - 1) {
+ var nonRestCount = paramCount - (restType ? 1 : 0);
+ if (restType && pos === nonRestCount) {
return restType;
}
- var start = restType ? Math.min(pos, paramCount - 1) : pos;
var types = [];
var names = [];
- for (var i = start; i < paramCount; i++) {
+ for (var i = pos; i < nonRestCount; i++) {
types.push(getTypeAtPosition(source, i));
names.push(getParameterNameAtPosition(source, i));
}
+ if (restType) {
+ types.push(getIndexedAccessType(restType, numberType));
+ names.push(getParameterNameAtPosition(source, nonRestCount));
+ }
var minArgumentCount = getMinArgumentCount(source);
- var minLength = minArgumentCount < start ? 0 : minArgumentCount - start;
- return createTupleType(types, minLength, !!restType, names);
+ var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos;
+ return createTupleType(types, minLength, !!restType, /*readonly*/ false, names);
}
function getParameterCount(signature) {
var length = signature.parameters.length;
@@ -50662,16 +51336,27 @@
function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
}
- function inferFromAnnotatedParameters(signature, context, mapper) {
+ function inferFromAnnotatedParameters(signature, context, inferenceContext) {
var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
for (var i = 0; i < len; i++) {
var declaration = signature.parameters[i].valueDeclaration;
if (declaration.type) {
var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
if (typeNode) {
- inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
+ inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
+ }
}
}
+ var restType = getEffectiveRestType(context);
+ if (restType && restType.flags & 262144 /* TypeParameter */) {
+ // The contextual signature has a generic rest parameter. We first instantiate the contextual
+ // signature (without fixing type parameters) and assign types to contextually typed parameters.
+ var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
+ assignContextualParameterTypes(signature, instantiatedContext);
+ // We then infer from a tuple type representing the parameters that correspond to the contextual
+ // rest parameter.
+ var restPos = getParameterCount(context) - 1;
+ inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
}
}
function assignContextualParameterTypes(signature, context) {
@@ -50773,7 +51458,7 @@
var functionFlags = ts.getFunctionFlags(func);
var type;
if (func.body.kind !== 218 /* Block */) {
- type = checkExpressionCached(func.body, checkMode);
+ type = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -50951,7 +51636,7 @@
ts.forEachReturnStatement(func.body, function (returnStatement) {
var expr = returnStatement.expression;
if (expr) {
- var type = checkExpressionCached(expr, checkMode);
+ var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51044,7 +51729,7 @@
ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
checkNodeDeferred(node);
// The identityMapper object is used to indicate that function expressions are wildcards
- if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) {
+ if (checkMode && checkMode & 4 /* 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);
@@ -51054,7 +51739,7 @@
var returnType = getReturnTypeFromBody(node, checkMode);
var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
- returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */;
+ returnOnlyType.objectFlags |= 524288 /* NonInferrableType */;
return links_1.contextFreeType = returnOnlyType;
}
return anyFunctionType;
@@ -51080,12 +51765,12 @@
if (contextualSignature) {
var signature = getSignaturesOfType(type, 0 /* Call */)[0];
if (isContextSensitive(node)) {
- var contextualMapper = getContextualMapper(node);
- if (checkMode === 2 /* Inferential */) {
- inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper);
+ var inferenceContext = getInferenceContext(node);
+ if (checkMode && checkMode & 2 /* Inferential */) {
+ inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
}
- var instantiatedContextualSignature = contextualMapper === identityMapper ?
- contextualSignature : instantiateSignature(contextualSignature, contextualMapper);
+ var instantiatedContextualSignature = inferenceContext ?
+ instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
assignContextualParameterTypes(signature, instantiatedContextualSignature);
}
if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
@@ -51351,13 +52036,13 @@
// Return true if type might be of the given kind. A union or intersection type might be of a given
// kind if at least one constituent type is of the given kind.
function maybeTypeOfKind(type, kind) {
- if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) {
+ if (type.flags & kind & ~131072 /* GenericMappedType */ || kind & 131072 /* GenericMappedType */ && isGenericMappedType(type)) {
return true;
}
if (type.flags & 3145728 /* UnionOrIntersection */) {
var types = type.types;
- for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
- var t = types_15[_i];
+ for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
+ var t = types_16[_i];
if (maybeTypeOfKind(t, kind)) {
return true;
}
@@ -51436,8 +52121,8 @@
if (strictNullChecks && properties.length === 0) {
return checkNonNullType(sourceType, node);
}
- for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) {
- var p = properties_6[_i];
+ for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
+ var p = properties_5[_i];
checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis);
}
return sourceType;
@@ -51461,7 +52146,7 @@
return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
}
else if (property.kind === 277 /* SpreadAssignment */) {
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(property, 4 /* Rest */);
}
var nonRestNames = [];
@@ -51956,7 +52641,7 @@
// Async generator functions prior to ESNext require the __await, __asyncDelegator,
// and __asyncValues helpers
if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ &&
- languageVersion < 6 /* ESNext */) {
+ languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */);
}
// Generator functions prior to ES2015 require the __values helper
@@ -52003,23 +52688,26 @@
}
return node;
}
- function checkExpressionWithContextualType(node, contextualType, contextualMapper) {
+ function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
var context = getContextNode(node);
var saveContextualType = context.contextualType;
- var saveContextualMapper = context.contextualMapper;
+ var saveInferenceContext = context.inferenceContext;
context.contextualType = contextualType;
- context.contextualMapper = contextualMapper;
- var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ :
- contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */;
- var result = checkExpression(node, checkMode);
+ context.inferenceContext = inferenceContext;
+ var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
+ // We strip literal freshness when an appropriate contextual type is present such that contextually typed
+ // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
+ // here would be to not mark contextually typed literals as fresh in the first place.
+ var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
+ getRegularTypeOfLiteralType(type) : type;
context.contextualType = saveContextualType;
- context.contextualMapper = saveContextualMapper;
+ context.inferenceContext = saveInferenceContext;
return result;
}
function checkExpressionCached(node, checkMode) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- if (checkMode) {
+ if (checkMode && checkMode !== 0 /* Normal */) {
return checkExpression(node, checkMode);
}
// When computing a type that we're going to cache, we need to ignore any ongoing control flow
@@ -52082,13 +52770,17 @@
}
return false;
}
- function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
- if (arguments.length === 2) {
- contextualType = getContextualType(node);
+ function isConstContext(node) {
+ var parent = node.parent;
+ return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
+ (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
+ (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
}
+ function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
var type = checkExpression(node, checkMode, forceTuple);
- return isTypeAssertion(node) ? type :
- getWidenedLiteralLikeTypeForContextualType(type, contextualType);
+ return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
+ isTypeAssertion(node) ? type :
+ getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
}
function checkPropertyAssignment(node, checkMode) {
// Do not use hasDynamicName here, because that returns false for well known symbols.
@@ -52112,20 +52804,129 @@
return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
}
function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
+ if (checkMode & 8 /* SkipGenericFunctions */) {
+ skippedGenericFunction(node, checkMode);
+ return anyFunctionType;
+ }
var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType));
if (contextualSignature && !contextualSignature.typeParameters) {
- return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node)));
+ var context = getInferenceContext(node);
+ // We have an expression that is an argument of a generic function for which we are performing
+ // type argument inference. The expression is of a function type with a single generic call
+ // signature and a contextual function type with a single non-generic call signature. Now check
+ // if the outer function returns a function type with a single non-generic call signature and
+ // if some of the outer function type parameters have no inferences so far. If so, we can
+ // potentially add inferred type parameters to the outer function return type.
+ var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature));
+ if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
+ // Instantiate the signature with its own type parameters as type arguments, possibly
+ // renaming the type parameters to ensure they have unique names.
+ var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
+ // Infer from the parameters of the instantiated signature to the parameters of the
+ // contextual signature starting with an empty set of inference candidates.
+ var inferences_2 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
+ applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
+ inferTypes(inferences_2, source, target, /*priority*/ 0, /*contravariant*/ true);
+ });
+ if (ts.some(inferences_2, hasInferenceCandidates)) {
+ // We have inference candidates, indicating that one or more type parameters are referenced
+ // in the parameter types of the contextual signature. Now also infer from the return type.
+ applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
+ inferTypes(inferences_2, source, target);
+ });
+ // If the type parameters for which we produced candidates do not have any inferences yet,
+ // we adopt the new inference candidates and add the type parameters of the expression type
+ // to the set of inferred type parameters for the outer function return type.
+ if (!hasOverlappingInferences(context.inferences, inferences_2)) {
+ mergeInferences(context.inferences, inferences_2);
+ context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
+ return getOrCreateTypeFromSignature(instantiatedSignature);
+ }
+ }
+ }
+ return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
}
}
}
}
return type;
}
+ function skippedGenericFunction(node, checkMode) {
+ if (checkMode & 2 /* Inferential */) {
+ // We have skipped a generic function during inferential typing. Obtain the inference context and
+ // indicate this has occurred such that we know a second pass of inference is be needed.
+ var context = getInferenceContext(node);
+ context.flags |= 4 /* SkippedGenericFunction */;
+ }
+ }
+ function hasInferenceCandidates(info) {
+ return !!(info.candidates || info.contraCandidates);
+ }
+ function hasOverlappingInferences(a, b) {
+ for (var i = 0; i < a.length; i++) {
+ if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ function mergeInferences(target, source) {
+ for (var i = 0; i < target.length; i++) {
+ if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
+ target[i] = source[i];
+ }
+ }
+ }
+ function getUniqueTypeParameters(context, typeParameters) {
+ var result = [];
+ var oldTypeParameters;
+ var newTypeParameters;
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var tp = typeParameters_2[_i];
+ var name = tp.symbol.escapedName;
+ if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
+ var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
+ var symbol = createSymbol(262144 /* TypeParameter */, newName);
+ var newTypeParameter = createTypeParameter(symbol);
+ newTypeParameter.target = tp;
+ oldTypeParameters = ts.append(oldTypeParameters, tp);
+ newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
+ result.push(newTypeParameter);
+ }
+ else {
+ result.push(tp);
+ }
+ }
+ if (newTypeParameters) {
+ var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
+ for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
+ var tp = newTypeParameters_1[_a];
+ tp.mapper = mapper;
+ }
+ }
+ return result;
+ }
+ function hasTypeParameterByName(typeParameters, name) {
+ return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
+ }
+ function getUniqueTypeParameterName(typeParameters, baseName) {
+ var len = baseName.length;
+ while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
+ len--;
+ var s = baseName.slice(0, len);
+ for (var index = 1; true; index++) {
+ var augmentedName = (s + index);
+ if (!hasTypeParameterByName(typeParameters, augmentedName)) {
+ return augmentedName;
+ }
+ }
+ }
/**
* Returns the type of an expression. Unlike checkExpression, this function is simply concerned
* with computing the type and may not fully check all contained sub-expressions for errors.
@@ -52143,7 +52944,7 @@
return getReturnTypeOfSignature(signature);
}
}
- else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) {
+ else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
return getTypeFromTypeNode(expr.type);
}
// Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions
@@ -52165,27 +52966,22 @@
}
var saveContextualType = node.contextualType;
node.contextualType = anyType;
- var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */);
+ var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
node.contextualType = saveContextualType;
return type;
}
- // 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
- // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function
- // object, it serves as an indicator that all contained function and arrow expressions should be considered to
- // have the wildcard function type; this form of type check is used during overload resolution to exclude
- // contextually typed function and arrow expressions in the initial phase.
function checkExpression(node, checkMode, forceTuple) {
- var type;
- if (node.kind === 148 /* QualifiedName */) {
- type = checkQualifiedName(node);
- }
- else {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
- type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
- }
+ var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
if (isConstEnumObjectType(type)) {
+ checkConstEnumAccess(node, type);
+ }
+ currentNode = saveCurrentNode;
+ return type;
+ }
+ function checkConstEnumAccess(node, type) {
// enum object type for const enums are only permitted in:
// - 'left' in property access
// - 'object' in indexed access
@@ -52197,8 +52993,13 @@
if (!ok) {
error(node, ts.Diagnostics.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);
}
+ if (compilerOptions.isolatedModules) {
+ ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
+ var constEnumDeclaration = type.symbol.valueDeclaration;
+ if (constEnumDeclaration.flags & 4194304 /* Ambient */) {
+ error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
+ }
}
- return type;
}
function checkParenthesizedExpression(node, checkMode) {
var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
@@ -52240,6 +53041,8 @@
return checkObjectLiteral(node, checkMode);
case 189 /* PropertyAccessExpression */:
return checkPropertyAccessExpression(node);
+ case 148 /* QualifiedName */:
+ return checkQualifiedName(node);
case 190 /* ElementAccessExpression */:
return checkIndexedAccess(node);
case 191 /* CallExpression */:
@@ -52248,7 +53051,7 @@
}
/* falls through */
case 192 /* NewExpression */:
- return checkCallExpression(node);
+ return checkCallExpression(node, checkMode);
case 193 /* TaggedTemplateExpression */:
return checkTaggedTemplateExpression(node);
case 195 /* ParenthesizedExpression */:
@@ -52313,9 +53116,8 @@
checkSourceElement(node.constraint);
checkSourceElement(node.default);
var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
- if (!hasNonCircularBaseConstraint(typeParameter)) {
- error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter));
- }
+ // Resolve base constraint to reveal circularity errors
+ getBaseConstraintOfType(typeParameter);
if (!hasNonCircularTypeParameterDefault(typeParameter)) {
error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
}
@@ -52357,7 +53159,7 @@
}
// 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) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) {
+ if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) {
error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
}
}
@@ -52368,7 +53170,8 @@
error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
return;
}
- var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent));
+ var signature = getSignatureFromDeclaration(parent);
+ var typePredicate = getTypePredicateOfSignature(signature);
if (!typePredicate) {
return;
}
@@ -52379,12 +53182,12 @@
}
else {
if (typePredicate.parameterIndex >= 0) {
- if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) {
+ if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) {
error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
}
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]), node.type,
+ checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type,
/*headMessage*/ undefined, leadingError);
}
}
@@ -52451,7 +53254,7 @@
var functionFlags = ts.getFunctionFlags(node);
if (!(functionFlags & 4 /* Invalid */)) {
// Async generators prior to ESNext require the __await and __asyncGenerator helpers
- if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) {
+ if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */);
}
// Async functions prior to ES2017 require the __awaiter helper
@@ -52508,7 +53311,7 @@
checkAsyncFunctionReturnType(node, returnTypeNode);
}
}
- if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) {
+ if (node.kind !== 162 /* IndexSignature */ && node.kind !== 294 /* JSDocFunctionType */) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -53187,7 +53990,7 @@
for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) {
var signature = signatures_6[_a];
if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
- error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation);
+ ts.addRelatedInfo(error(signature.declaration, ts.Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), ts.createDiagnosticForNode(bodyDeclaration, ts.Diagnostics.The_implementation_signature_is_declared_here));
break;
}
}
@@ -53264,8 +54067,8 @@
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
// A jsdoc typedef and callback are, by definition, type aliases
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return 2 /* ExportType */;
case 244 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
@@ -53274,7 +54077,7 @@
case 240 /* ClassDeclaration */:
case 243 /* EnumDeclaration */:
return 2 /* ExportType */ | 1 /* ExportValue */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
case 254 /* ExportAssignment */:
// Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
@@ -53639,8 +54442,8 @@
}
function getEntityNameForDecoratorMetadataFromTypeList(types) {
var commonEntityName;
- for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
- var typeNode = types_16[_i];
+ for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
+ var typeNode = types_17[_i];
while (typeNode.kind === 177 /* ParenthesizedType */) {
typeNode = typeNode.type; // Skip parens if need be
}
@@ -53915,7 +54718,7 @@
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
case 246 /* CaseBlock */:
@@ -54008,8 +54811,8 @@
return;
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];
+ for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
+ var typeParameter = typeParameters_3[_i];
if (!isTypeParameterUnused(typeParameter))
continue;
var name = ts.idText(typeParameter.name);
@@ -54262,7 +55065,7 @@
}
// 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 === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
+ if (parent.kind === 284 /* 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));
}
@@ -54277,7 +55080,7 @@
}
// 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 === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
+ if (parent.kind === 284 /* 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));
}
@@ -54334,7 +55137,7 @@
(container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) ||
container.kind === 245 /* ModuleBlock */ ||
container.kind === 244 /* ModuleDeclaration */ ||
- container.kind === 279 /* SourceFile */);
+ container.kind === 284 /* 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
@@ -54434,7 +55237,7 @@
}
}
if (node.kind === 186 /* BindingElement */) {
- if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) {
+ if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 4 /* Rest */);
}
// check computed properties inside property names of binding elements
@@ -54445,7 +55248,7 @@
var parent = node.parent.parent;
var parentType = getTypeForBindingElementParent(parent);
var name = node.propertyName || node.name;
- if (!ts.isBindingPattern(name) && parentType) {
+ if (parentType && !ts.isBindingPattern(name)) {
var exprType = getLiteralTypeFromPropertyName(name);
if (isTypeUsableAsPropertyName(exprType)) {
var nameText = getPropertyNameFromType(exprType);
@@ -54632,7 +55435,7 @@
checkGrammarForInOrForOfStatement(node);
if (node.awaitModifier) {
var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
- if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) {
+ if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 7 /* ESNext */) {
// for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */);
}
@@ -55077,7 +55880,7 @@
// If the function has a return type, but promisedType is
// undefined, an error will be reported in checkAsyncFunctionReturnType
// so we don't need to report one here.
- checkTypeAssignableTo(awaitedType, promisedType, node);
+ checkTypeAssignableToAndOptionallyElaborate(awaitedType, promisedType, node, node.expression);
}
}
else {
@@ -55677,8 +56480,8 @@
for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
var base = baseTypes_2[_i];
var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
- for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) {
- var prop = properties_7[_a];
+ for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
+ var prop = properties_6[_a];
var existing = seen.get(prop.escapedName);
if (!existing) {
seen.set(prop.escapedName, { prop: prop, containingType: base });
@@ -55948,10 +56751,6 @@
checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
checkExportsOnMergedDeclarations(node);
computeEnumMemberValues(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);
- }
// Spec 2014 - Section 9.3:
// It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
// and when an enum type has multiple declarations, only one declaration is permitted to omit a value
@@ -55962,9 +56761,10 @@
var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
if (node === firstDeclaration) {
if (enumSymbol.declarations.length > 1) {
+ var enumIsConst_1 = ts.isEnumConst(node);
// check that const is placed\omitted on all enum declarations
ts.forEach(enumSymbol.declarations, function (decl) {
- if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) {
+ if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
}
});
@@ -56045,8 +56845,8 @@
var symbol = getSymbolOfNode(node);
// The following checks only apply on a non-ambient instantiated module declaration.
if (symbol.flags & 512 /* ValueModule */
- && symbol.declarations.length > 1
&& !inAmbientContext
+ && symbol.declarations.length > 1
&& isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
if (firstNonAmbientClassOrFunc) {
@@ -56187,7 +56987,7 @@
return false;
}
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule) {
error(moduleName, node.kind === 255 /* ExportDeclaration */ ?
ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
@@ -56318,7 +57118,7 @@
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ &&
!node.moduleSpecifier && node.flags & 4194304 /* Ambient */;
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
}
}
@@ -56335,7 +57135,7 @@
}
}
function checkGrammarModuleElementContext(node, errorMessage) {
- var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
+ var isInAppropriateContext = node.parent.kind === 284 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
if (!isInAppropriateContext) {
grammarErrorOnFirstToken(node, errorMessage);
}
@@ -56364,7 +57164,7 @@
// If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
return;
}
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
if (node.isExportEquals) {
error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
@@ -56457,9 +57257,14 @@
!!declaration.body;
}
function checkSourceElement(node) {
- if (!node) {
- return;
+ if (node) {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
+ checkSourceElementWorker(node);
+ currentNode = saveCurrentNode;
+ }
}
+ function checkSourceElementWorker(node) {
if (ts.isInJSFile(node)) {
ts.forEach(node.jsDoc, function (_a) {
var tags = _a.tags;
@@ -56529,32 +57334,32 @@
return checkInferType(node);
case 183 /* ImportType */:
return checkImportType(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return checkJSDocAugmentsTag(node);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return checkJSDocTypeAliasTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return checkJSDocTemplateTag(node);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return checkJSDocTypeTag(node);
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
return checkJSDocParameterTag(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
checkJSDocFunctionType(node);
// falls through
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
- case 292 /* JSDocTypeLiteral */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
+ case 297 /* JSDocTypeLiteral */:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
checkJSDocVariadicType(node);
return;
- case 283 /* JSDocTypeExpression */:
+ case 288 /* JSDocTypeExpression */:
return checkSourceElement(node.type);
case 180 /* IndexedAccessType */:
return checkIndexedAccessType(node);
@@ -56708,10 +57513,13 @@
}
function checkDeferredNodes(context) {
var links = getNodeLinks(context);
- if (!links.deferredNodes) {
- return;
+ if (links.deferredNodes) {
+ links.deferredNodes.forEach(checkDeferredNode);
}
- links.deferredNodes.forEach(function (node) {
+ }
+ function checkDeferredNode(node) {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
switch (node.kind) {
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
@@ -56733,7 +57541,7 @@
checkJsxElementDeferred(node);
break;
}
- });
+ currentNode = saveCurrentNode;
}
function checkSourceFile(node) {
ts.performance.mark("beforeCheck");
@@ -56808,7 +57616,7 @@
throwIfNonDiagnosticsProducing();
if (sourceFile) {
// Some global diagnostics are deferred until they are needed and
- // may not be reported in the firt call to getGlobalDiagnostics.
+ // may not be reported in the first call to getGlobalDiagnostics.
// We should catch these changes and report them.
var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
@@ -56859,7 +57667,7 @@
copySymbols(location.locals, meaning);
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
// falls through
@@ -57078,10 +57886,10 @@
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 299 /* JSDocParameterTag */) {
+ if (entityName.parent.kind === 304 /* JSDocParameterTag */) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) {
+ if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 308 /* JSDocTemplateTag */) {
ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true.
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -57123,7 +57931,7 @@
return undefined;
}
function getSymbolAtLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
}
var parent = node.parent;
@@ -57465,7 +58273,7 @@
}
var parentSymbol_1 = getParentOfSymbol(symbol);
if (parentSymbol_1) {
- if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) {
+ if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 284 /* 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.
@@ -57492,7 +58300,7 @@
return undefined;
}
function isSymbolOfDeclarationWithCollidingName(symbol) {
- if (symbol.flags & 418 /* BlockScoped */) {
+ if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
var links = getSymbolLinks(symbol);
if (links.isDeclarationWithCollidingName === undefined) {
var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
@@ -57580,7 +58388,7 @@
}
function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
- if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
+ if (node === undefined || node.parent.kind !== 284 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
// parent is not source file or it is not reference to internal module
return false;
}
@@ -58009,7 +58817,7 @@
break;
}
}
- if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
+ if (current.valueDeclaration && current.valueDeclaration.kind === 284 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
return false;
}
// check that at least one declaration of top level symbol originates from type declaration file
@@ -58042,7 +58850,7 @@
if (!moduleSymbol) {
return undefined;
}
- return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */);
+ return ts.getDeclarationOfKind(moduleSymbol, 284 /* SourceFile */);
}
function initializeTypeChecker() {
// Bind all source files and propagate errors
@@ -58120,7 +58928,7 @@
// autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
}
- globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1);
+ globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
if (augmentations) {
@@ -58156,8 +58964,8 @@
else {
// Otherwise issue top-level error since the files appear very identical in terms of what they contain
var list = ts.arrayFrom(conflictingSymbols.keys()).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)));
+ diagnostics.add(ts.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(ts.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;
@@ -58274,7 +59082,7 @@
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
}
else if (flags & 128 /* Abstract */) {
@@ -58297,7 +59105,7 @@
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
}
else if (node.kind === 151 /* Parameter */) {
@@ -58342,7 +59150,7 @@
flags |= 1 /* Export */;
break;
case 80 /* DefaultKeyword */:
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
}
@@ -58465,7 +59273,7 @@
case 151 /* Parameter */:
return false;
default:
- if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return false;
}
switch (node.kind) {
@@ -58553,10 +59361,10 @@
var nonSimpleParameters = getNonSimpleParameters(node.parameters);
if (ts.length(nonSimpleParameters)) {
ts.forEach(nonSimpleParameters, function (parameter) {
- addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
+ ts.addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
});
var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); });
- addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
+ ts.addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
return true;
}
}
@@ -58993,6 +59801,11 @@
return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
}
}
+ else if (node.operator === 133 /* ReadonlyKeyword */) {
+ if (node.type.kind !== 169 /* ArrayType */ && node.type.kind !== 170 /* TupleType */) {
+ return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(139 /* SymbolKeyword */));
+ }
+ }
}
function checkGrammarForInvalidDynamicName(node, message) {
if (isNonBindableDynamicName(node)) {
@@ -59383,7 +60196,7 @@
// 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 === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
var links_2 = getNodeLinks(node.parent);
// Check if the containing block ever report this error
if (!links_2.hasReportedStatementInAmbientContext) {
@@ -59423,7 +60236,7 @@
var literalType = ts.isLiteralTypeNode(node.parent) ||
ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
if (!literalType) {
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) {
return true;
}
@@ -59588,10 +60401,11 @@
return createLiteralFromNode(value);
}
ts.createLiteral = createLiteral;
- function createNumericLiteral(value) {
+ function createNumericLiteral(value, numericLiteralFlags) {
+ if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
var node = createSynthesizedNode(8 /* NumericLiteral */);
node.text = value;
- node.numericLiteralFlags = 0;
+ node.numericLiteralFlags = numericLiteralFlags;
return node;
}
ts.createNumericLiteral = createNumericLiteral;
@@ -61436,14 +62250,14 @@
// JSDoc
/* @internal */
function createJSDocTypeExpression(type) {
- var node = createSynthesizedNode(283 /* JSDocTypeExpression */);
+ var node = createSynthesizedNode(288 /* JSDocTypeExpression */);
node.type = type;
return node;
}
ts.createJSDocTypeExpression = createJSDocTypeExpression;
/* @internal */
function createJSDocTypeTag(typeExpression, comment) {
- var tag = createJSDocTag(302 /* JSDocTypeTag */, "type");
+ var tag = createJSDocTag(307 /* JSDocTypeTag */, "type");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61451,7 +62265,7 @@
ts.createJSDocTypeTag = createJSDocTypeTag;
/* @internal */
function createJSDocReturnTag(typeExpression, comment) {
- var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns");
+ var tag = createJSDocTag(305 /* JSDocReturnTag */, "returns");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61459,7 +62273,7 @@
ts.createJSDocReturnTag = createJSDocReturnTag;
/* @internal */
function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
- var tag = createJSDocTag(299 /* JSDocParameterTag */, "param");
+ var tag = createJSDocTag(304 /* JSDocParameterTag */, "param");
tag.typeExpression = typeExpression;
tag.name = name;
tag.isBracketed = isBracketed;
@@ -61469,7 +62283,7 @@
ts.createJSDocParamTag = createJSDocParamTag;
/* @internal */
function createJSDocComment(comment, tags) {
- var node = createSynthesizedNode(291 /* JSDocComment */);
+ var node = createSynthesizedNode(296 /* JSDocComment */);
node.comment = comment;
node.tags = tags;
return node;
@@ -61550,6 +62364,28 @@
return node;
}
ts.createJsxFragment = createJsxFragment;
+ function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
+ var node = createSynthesizedNode(11 /* JsxText */);
+ node.text = text;
+ node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
+ return node;
+ }
+ ts.createJsxText = createJsxText;
+ function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
+ return node.text !== text
+ || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
+ ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
+ : node;
+ }
+ ts.updateJsxText = updateJsxText;
+ function createJsxOpeningFragment() {
+ return createSynthesizedNode(265 /* JsxOpeningFragment */);
+ }
+ ts.createJsxOpeningFragment = createJsxOpeningFragment;
+ function createJsxJsxClosingFragment() {
+ return createSynthesizedNode(266 /* JsxClosingFragment */);
+ }
+ ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment;
function updateJsxFragment(node, openingFragment, children, closingFragment) {
return node.openingFragment !== openingFragment
|| node.children !== children
@@ -61728,7 +62564,7 @@
(typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
(libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
(hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
- var updated = createSynthesizedNode(279 /* SourceFile */);
+ var updated = createSynthesizedNode(284 /* SourceFile */);
updated.flags |= node.flags;
updated.statements = createNodeArray(statements);
updated.endOfFileToken = node.endOfFileToken;
@@ -61812,7 +62648,7 @@
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(307 /* NotEmittedStatement */);
+ var node = createSynthesizedNode(312 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
@@ -61824,7 +62660,7 @@
*/
/* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(316 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -61836,7 +62672,7 @@
*/
/* @internal */
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(310 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(315 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -61851,7 +62687,7 @@
* @param location The location for the expression. Defaults to the positions from "original" if provided.
*/
function createPartiallyEmittedExpression(expression, original) {
- var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */);
+ var node = createSynthesizedNode(313 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -61867,7 +62703,7 @@
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
function flattenCommaElements(node) {
if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
- if (node.kind === 309 /* CommaListExpression */) {
+ if (node.kind === 314 /* CommaListExpression */) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
@@ -61877,7 +62713,7 @@
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(309 /* CommaListExpression */);
+ var node = createSynthesizedNode(314 /* CommaListExpression */);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -61890,33 +62726,197 @@
ts.updateCommaList = updateCommaList;
function createBundle(sourceFiles, prepends) {
if (prepends === void 0) { prepends = ts.emptyArray; }
- var node = ts.createNode(280 /* Bundle */);
+ var node = ts.createNode(285 /* Bundle */);
node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, map) {
- var node = ts.createNode(281 /* UnparsedSource */);
+ var allUnscopedEmitHelpers;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
+ ts.valuesHelper,
+ ts.readHelper,
+ ts.spreadHelper,
+ ts.restHelper,
+ ts.decorateHelper,
+ ts.metadataHelper,
+ ts.paramHelper,
+ ts.awaiterHelper,
+ ts.assignHelper,
+ ts.awaitHelper,
+ ts.asyncGeneratorHelper,
+ ts.asyncDelegator,
+ ts.asyncValues,
+ ts.extendsHelper,
+ ts.templateObjectHelper,
+ ts.generatorHelper,
+ ts.importStarHelper,
+ ts.importDefaultHelper
+ ], function (helper) { return helper.name; }));
+ }
+ function createUnparsedSource() {
+ var node = ts.createNode(286 /* UnparsedSource */);
+ node.prologues = ts.emptyArray;
+ node.referencedFiles = ts.emptyArray;
+ node.libReferenceDirectives = ts.emptyArray;
+ node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
+ return node;
+ }
+ function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
+ var node = createUnparsedSource();
+ var stripInternal;
+ var bundleFileInfo;
if (!ts.isString(textOrInputFiles)) {
ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
- node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath;
+ node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
Object.defineProperties(node, {
text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
});
+ if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
+ node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
+ ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
+ stripInternal = mapTextOrStripInternal;
+ bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
+ if (node.oldFileOfCurrentEmit) {
+ parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo));
+ return node;
+ }
+ }
}
else {
+ node.fileName = "";
node.text = textOrInputFiles;
node.sourceMapPath = mapPathOrType;
- node.sourceMapText = map;
+ node.sourceMapText = mapTextOrStripInternal;
}
+ ts.Debug.assert(!node.oldFileOfCurrentEmit);
+ parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
return node;
}
ts.createUnparsedSourceFile = createUnparsedSourceFile;
- function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapText) {
- var node = ts.createNode(282 /* InputFiles */);
+ function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
+ var prologues;
+ var helpers;
+ var referencedFiles;
+ var typeReferenceDirectives;
+ var libReferenceDirectives;
+ var texts;
+ for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "prologue" /* Prologue */:
+ (prologues || (prologues = [])).push(createUnparsedNode(section, node));
+ break;
+ case "emitHelpers" /* EmitHelpers */:
+ (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ node.hasNoDefaultLib = true;
+ break;
+ case "reference" /* Reference */:
+ (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "type" /* Type */:
+ (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
+ break;
+ case "lib" /* Lib */:
+ (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "prepend" /* Prepend */:
+ var prependNode = createUnparsedNode(section, node);
+ var prependTexts = void 0;
+ for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
+ var text = _c[_b];
+ if (!stripInternal || text.kind !== "internal" /* Internal */) {
+ (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
+ }
+ }
+ prependNode.texts = prependTexts || ts.emptyArray;
+ (texts || (texts = [])).push(prependNode);
+ break;
+ case "internal" /* Internal */:
+ if (stripInternal)
+ break;
+ // falls through
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.prologues = prologues || ts.emptyArray;
+ node.helpers = helpers;
+ node.referencedFiles = referencedFiles || ts.emptyArray;
+ node.typeReferenceDirectives = typeReferenceDirectives;
+ node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
+ node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
+ }
+ function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
+ ts.Debug.assert(!!node.oldFileOfCurrentEmit);
+ var texts;
+ var syntheticReferences;
+ for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "internal" /* Internal */:
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
+ break;
+ // Ignore
+ case "prologue" /* Prologue */:
+ case "emitHelpers" /* EmitHelpers */:
+ case "prepend" /* Prepend */:
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.texts = texts || ts.emptyArray;
+ node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
+ node.syntheticReferences = syntheticReferences;
+ return node;
+ }
+ function mapBundleFileSectionKindToSyntaxKind(kind) {
+ switch (kind) {
+ case "prologue" /* Prologue */: return 279 /* UnparsedPrologue */;
+ case "prepend" /* Prepend */: return 280 /* UnparsedPrepend */;
+ case "internal" /* Internal */: return 282 /* UnparsedInternalText */;
+ case "text" /* Text */: return 281 /* UnparsedText */;
+ case "emitHelpers" /* EmitHelpers */:
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
+ default:
+ return ts.Debug.assertNever(kind);
+ }
+ }
+ function createUnparsedNode(section, parent) {
+ var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ return node;
+ }
+ function createUnparsedSyntheticReference(section, parent) {
+ var node = ts.createNode(283 /* UnparsedSyntheticReference */, section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ node.section = section;
+ return node;
+ }
+ function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
+ var node = ts.createNode(287 /* InputFiles */);
if (!ts.isString(javascriptTextOrReadFileText)) {
var cache_1 = ts.createMap();
var textGetter_1 = function (path) {
@@ -61933,15 +62933,25 @@
var result = textGetter_1(path);
return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
};
+ var buildInfo_1;
+ var getAndCacheBuildInfo_1 = function (getText) {
+ if (buildInfo_1 === undefined) {
+ var result = getText();
+ buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
+ }
+ return buildInfo_1 || undefined;
+ };
node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath;
node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath;
+ node.buildInfoPath = declarationMapTextOrBuildInfoPath;
Object.defineProperties(node, {
javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
- declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } } // TODO:: if there is inline sourceMap in dtsFile, use that
+ declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
+ buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
});
}
else {
@@ -61950,7 +62960,12 @@
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
node.declarationText = declarationTextOrJavascriptPath;
node.declarationMapPath = declarationMapPath;
- node.declarationMapText = declarationMapText;
+ node.declarationMapText = declarationMapTextOrBuildInfoPath;
+ node.javascriptPath = javascriptPath;
+ node.declarationPath = declarationPath,
+ node.buildInfoPath = buildInfoPath;
+ node.buildInfo = buildInfo;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
}
return node;
}
@@ -62088,10 +63103,10 @@
// 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 === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return node.emitNode = { annotatedNodes: [node] };
}
- var sourceFile = ts.getSourceFileOfNode(node);
+ var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
}
node.emitNode = {};
@@ -62389,7 +63404,7 @@
ts.nullTransformationContext = {
enableEmitNotification: ts.noop,
enableSubstitution: ts.noop,
- endLexicalEnvironment: function () { return undefined; },
+ endLexicalEnvironment: ts.returnUndefined,
getCompilerOptions: ts.notImplemented,
getEmitHost: ts.notImplemented,
getEmitResolver: ts.notImplemented,
@@ -62534,38 +63549,38 @@
return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
}
ts.getHelperName = getHelperName;
- var valuesHelper = {
+ ts.valuesHelper = {
name: "typescript:values",
scoped: false,
text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };"
};
function createValuesHelper(context, expression, location) {
- context.requestEmitHelper(valuesHelper);
+ context.requestEmitHelper(ts.valuesHelper);
return ts.setTextRange(ts.createCall(getHelperName("__values"),
/*typeArguments*/ undefined, [expression]), location);
}
ts.createValuesHelper = createValuesHelper;
- var readHelper = {
+ ts.readHelper = {
name: "typescript:read",
scoped: false,
text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };"
};
function createReadHelper(context, iteratorRecord, count, location) {
- context.requestEmitHelper(readHelper);
+ context.requestEmitHelper(ts.readHelper);
return ts.setTextRange(ts.createCall(getHelperName("__read"),
/*typeArguments*/ undefined, count !== undefined
? [iteratorRecord, ts.createLiteral(count)]
: [iteratorRecord]), location);
}
ts.createReadHelper = createReadHelper;
- var spreadHelper = {
+ ts.spreadHelper = {
name: "typescript:spread",
scoped: false,
text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
};
function createSpreadHelper(context, argumentList, location) {
- context.requestEmitHelper(readHelper);
- context.requestEmitHelper(spreadHelper);
+ context.requestEmitHelper(ts.readHelper);
+ context.requestEmitHelper(ts.spreadHelper);
return ts.setTextRange(ts.createCall(getHelperName("__spread"),
/*typeArguments*/ undefined, argumentList), location);
}
@@ -62736,7 +63751,7 @@
function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) {
var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
if (property === firstAccessor) {
- var properties_8 = [];
+ var properties_7 = [];
if (getAccessor) {
var getterFunction = ts.createFunctionExpression(getAccessor.modifiers,
/*asteriskToken*/ undefined,
@@ -62747,7 +63762,7 @@
ts.setTextRange(getterFunction, getAccessor);
ts.setOriginalNode(getterFunction, getAccessor);
var getter = ts.createPropertyAssignment("get", getterFunction);
- properties_8.push(getter);
+ properties_7.push(getter);
}
if (setAccessor) {
var setterFunction = ts.createFunctionExpression(setAccessor.modifiers,
@@ -62759,15 +63774,15 @@
ts.setTextRange(setterFunction, setAccessor);
ts.setOriginalNode(setterFunction, setAccessor);
var setter = ts.createPropertyAssignment("set", setterFunction);
- properties_8.push(setter);
+ properties_7.push(setter);
}
- properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
- properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
+ properties_7.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
+ properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"),
/*typeArguments*/ undefined, [
receiver,
createExpressionForPropertyName(property.name),
- ts.createObjectLiteral(properties_8, multiLine)
+ ts.createObjectLiteral(properties_7, multiLine)
]),
/*location*/ firstAccessor);
return ts.aggregateTransformFlags(expression);
@@ -63411,7 +64426,7 @@
case 190 /* ElementAccessExpression */:
case 189 /* PropertyAccessExpression */:
case 213 /* NonNullExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -63427,7 +64442,7 @@
ts.parenthesizeConciseBody = parenthesizeConciseBody;
function isCommaSequence(node) {
return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
- node.kind === 309 /* CommaListExpression */;
+ node.kind === 314 /* CommaListExpression */;
}
ts.isCommaSequence = isCommaSequence;
var OuterExpressionKinds;
@@ -63446,7 +64461,7 @@
case 212 /* AsExpression */:
case 213 /* NonNullExpression */:
return (kinds & 2 /* Assertions */) !== 0;
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
}
return false;
@@ -63483,7 +64498,7 @@
case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
- case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 313 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
/**
@@ -64275,12 +65290,12 @@
case 278 /* EnumMember */:
return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
// No need to visit nodes with no children.
@@ -64336,7 +65351,7 @@
case 220 /* EmptyStatement */:
case 210 /* OmittedExpression */:
case 236 /* DebuggerStatement */:
- case 307 /* NotEmittedStatement */:
+ case 312 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
@@ -64713,14 +65728,14 @@
result = reduceNode(node.initializer, cbNode, result);
break;
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
result = reduceNodes(node.statements, cbNodes, result);
break;
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -64734,8 +65749,8 @@
return statements;
}
return ts.isNodeArray(statements)
- ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements)
- : ts.addStatementsAfterPrologue(statements, declarations);
+ ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements)
+ : ts.insertStatementsAfterStandardPrologue(statements, declarations);
}
ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
/**
@@ -65001,7 +66016,7 @@
}
exit();
}
- function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) {
+ function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
var _a;
ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
@@ -65011,6 +66026,14 @@
var nameIndexToNewNameIndexMap;
var mappingIterator = decodeMappings(map.mappings);
for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) {
+ if (end && (raw.generatedLine > end.line ||
+ (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
+ break;
+ }
+ if (start && (raw.generatedLine < start.line ||
+ (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
+ continue;
+ }
// Then reencode all the updated mappings into the overall map
var newSourceIndex = void 0;
var newSourceLine = void 0;
@@ -65039,8 +66062,10 @@
}
}
}
- var newGeneratedLine = raw.generatedLine + generatedLine;
- var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter;
+ var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
+ var newGeneratedLine = rawGeneratedLine + generatedLine;
+ var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
+ var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
}
exit();
@@ -65523,7 +66548,7 @@
function chainBundle(transformSourceFile) {
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
+ return node.kind === 284 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
}
function transformBundle(node) {
return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
@@ -65999,8 +67024,8 @@
if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
if (flattenContext.level >= 1 /* ObjectRest */
- && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */))
- && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */))
+ && !(element.transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */))
+ && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */))
&& !ts.isComputedPropertyName(propertyName)) {
bindingElements = ts.append(bindingElements, element);
}
@@ -66066,7 +67091,7 @@
if (flattenContext.level >= 1 /* ObjectRest */) {
// If an array pattern contains an ObjectRest, we must cache the result so that we
// can perform the ObjectRest destructuring in a different declaration
- if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (element.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
if (flattenContext.hoistTempVariables) {
flattenContext.context.hoistVariableDeclaration(temp);
@@ -66184,7 +67209,7 @@
function makeAssignmentElement(name) {
return name;
}
- var restHelper = {
+ ts.restHelper = {
name: "typescript:rest",
scoped: false,
text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
@@ -66193,7 +67218,7 @@
* `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
*/
function createRestCall(context, value, elements, computedTempVariables, location) {
- context.requestEmitHelper(restHelper);
+ context.requestEmitHelper(ts.restHelper);
var propertyNames = [];
var computedTempVariableOffset = 0;
for (var i = 0; i < elements.length - 1; i++) {
@@ -66294,14 +67319,14 @@
var pendingExpressions;
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* 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 === 282 /* InputFiles */) {
+ if (prepend.kind === 287 /* InputFiles */) {
return ts.createUnparsedSourceFile(prepend, "js");
}
return prepend;
@@ -66350,7 +67375,7 @@
*/
function onBeforeVisitNode(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 245 /* ModuleBlock */:
case 218 /* Block */:
@@ -66394,14 +67419,9 @@
* @param node The node to visit.
*/
function visitorWorker(node) {
- if (node.transformFlags & 1 /* TypeScript */) {
- // This node is explicitly marked as TypeScript, so we should transform the node.
+ if (node.transformFlags & 1 /* ContainsTypeScript */) {
return visitTypeScript(node);
}
- else if (node.transformFlags & 2 /* ContainsTypeScript */) {
- // This node contains TypeScript, so we should visit its children.
- return ts.visitEachChild(node, visitor, context);
- }
return node;
}
/**
@@ -66435,7 +67455,7 @@
// As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
// We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
// and will trigger debug failures when debug verbosity is turned up
- if (node.transformFlags & 2 /* ContainsTypeScript */) {
+ if (node.transformFlags & 1 /* ContainsTypeScript */) {
// This node contains TypeScript, so we should visit its children.
return ts.visitEachChild(node, visitor, context);
}
@@ -66477,15 +67497,9 @@
// do not emit ES6 imports and exports since they are illegal inside a namespace
return undefined;
}
- else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
- // This node is explicitly marked as TypeScript, or is exported at the namespace
- // level, so we should transform the node.
+ else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
return visitTypeScript(node);
}
- else if (node.transformFlags & 2 /* ContainsTypeScript */) {
- // This node contains TypeScript, so we should visit its children.
- return ts.visitEachChild(node, visitor, context);
- }
return node;
}
/**
@@ -66536,7 +67550,7 @@
* @param node The node to visit.
*/
function visitTypeScript(node) {
- if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) {
+ if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) {
// TypeScript ambient declarations are elided, but some comments may be preserved.
// See the implementation of `getLeadingComments` in comments.ts for more details.
return ts.createNotEmittedStatement(node);
@@ -66603,7 +67617,7 @@
// See the implementation of `getLeadingComments` in comments.ts for more details.
return ts.createNotEmittedStatement(node);
case 240 /* ClassDeclaration */:
- // This is a class declaration with TypeScript syntax extensions.
+ // This may be a class declaration with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
// - decorators
@@ -66614,7 +67628,7 @@
// - method overload signatures
return visitClassDeclaration(node);
case 209 /* ClassExpression */:
- // This is a class expression with TypeScript syntax extensions.
+ // This may be a class expression with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
// - decorators
@@ -66625,7 +67639,7 @@
// - method overload signatures
return visitClassExpression(node);
case 273 /* HeritageClause */:
- // This is a heritage clause with TypeScript syntax extensions.
+ // This may be a heritage clause with TypeScript syntax extensions.
//
// TypeScript heritage clause extensions include:
// - `implements` clause
@@ -66653,7 +67667,7 @@
// TypeScript arrow functions can have modifiers and type annotations.
return visitArrowFunction(node);
case 151 /* Parameter */:
- // This is a parameter declaration with TypeScript syntax extensions.
+ // This may be a parameter declaration with TypeScript syntax extensions.
//
// TypeScript parameter declaration syntax extensions include:
// - decorators
@@ -66694,7 +67708,8 @@
// TypeScript namespace or external module import.
return visitImportEqualsDeclaration(node);
default:
- return ts.Debug.failBadSyntaxKind(node);
+ // node contains some other TypeScript syntax
+ return ts.visitEachChild(node, visitor, context);
}
}
function visitSourceFile(node) {
@@ -66743,18 +67758,19 @@
facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
return facts;
}
- /**
- * Transforms a class declaration with TypeScript syntax into compatible ES6.
- *
- * This function will only be called when one of the following conditions are met:
- * - The class has decorators.
- * - The class has property declarations with initializers.
- * - The class contains a constructor that contains parameters with accessibility modifiers.
- * - The class is an export in a TypeScript namespace.
- *
- * @param node The node to transform.
- */
+ function hasTypeScriptClassSyntax(node) {
+ return !!(node.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */);
+ }
+ function isClassLikeDeclarationWithTypeScriptSyntax(node) {
+ return ts.some(node.decorators)
+ || ts.some(node.typeParameters)
+ || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
+ || ts.some(node.members, hasTypeScriptClassSyntax);
+ }
function visitClassDeclaration(node) {
+ if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) {
+ return ts.visitEachChild(node, visitor, context);
+ }
var savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
@@ -66807,7 +67823,7 @@
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
var iife = ts.createImmediatelyInvokedArrowFunction(statements);
ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
var varStatement = ts.createVariableStatement(
@@ -66984,16 +68000,10 @@
ts.setCommentRange(statement, node);
return statement;
}
- /**
- * Transforms a class expression with TypeScript syntax into compatible ES6.
- *
- * This function will only be called when one of the following conditions are met:
- * - The class has property declarations with initializers.
- * - The class contains a constructor that contains parameters with accessibility modifiers.
- *
- * @param node The node to transform.
- */
function visitClassExpression(node) {
+ if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
+ return ts.visitEachChild(node, visitor, context);
+ }
var savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
@@ -67057,7 +68067,7 @@
var constructor = ts.getFirstConstructorWithBody(node);
var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty);
var hasParameterPropertyAssignments = constructor &&
- constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ &&
+ constructor.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */ &&
ts.forEach(constructor.parameters, isParameterWithPropertyAssignment);
// If the class does not contain nodes that require a synthesized constructor,
// accept the current constructor if it exists.
@@ -67256,8 +68266,8 @@
* @param receiver The receiver on which each property should be assigned.
*/
function addInitializedPropertyStatements(statements, properties, receiver) {
- for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
- var property = properties_9[_i];
+ for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
+ var property = properties_8[_i];
var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver));
ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
ts.setCommentRange(statement, property);
@@ -67273,8 +68283,8 @@
*/
function generateInitializedPropertyExpressions(properties, receiver) {
var expressions = [];
- for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) {
- var property = properties_10[_i];
+ for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
+ var property = properties_9[_i];
var expression = transformInitializedProperty(property, receiver);
ts.startOnNewLine(expression);
ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
@@ -67348,11 +68358,14 @@
var decorators;
if (node) {
var parameters = node.parameters;
- for (var i = 0; i < parameters.length; i++) {
- var parameter = parameters[i];
+ var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
+ var firstParameterOffset = firstParameterIsThis ? 1 : 0;
+ var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
+ for (var i = 0; i < numParameters; i++) {
+ var parameter = parameters[i + firstParameterOffset];
if (decorators || parameter.decorators) {
if (!decorators) {
- decorators = new Array(parameters.length);
+ decorators = new Array(numParameters);
}
decorators[i] = parameter.decorators;
}
@@ -67852,8 +68865,12 @@
return serializeTypeList(node.types);
case 175 /* ConditionalType */:
return serializeTypeList([node.trueType, node.falseType]);
- case 167 /* TypeQuery */:
case 179 /* TypeOperator */:
+ if (node.operator === 133 /* ReadonlyKeyword */) {
+ return serializeTypeNode(node.type);
+ }
+ break;
+ case 167 /* TypeQuery */:
case 180 /* IndexedAccessType */:
case 181 /* MappedType */:
case 168 /* TypeLiteral */:
@@ -67871,8 +68888,8 @@
// Note when updating logic here also update getEntityNameForDecoratorMetadata
// so that aliases can be marked as referenced
var serializedUnion;
- for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
- var typeNode = types_17[_i];
+ for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
+ var typeNode = types_18[_i];
while (typeNode.kind === 177 /* ParenthesizedType */) {
typeNode = typeNode.type; // Skip parens if need be
}
@@ -68014,7 +69031,7 @@
* available.
*/
function getGlobalBigIntNameWithFallback() {
- return languageVersion < 6 /* ESNext */
+ return languageVersion < 7 /* ESNext */
? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object"))
: ts.createIdentifier("BigInt");
}
@@ -68098,12 +69115,12 @@
* @param node The HeritageClause to transform.
*/
function visitHeritageClause(node) {
- if (node.token === 86 /* ExtendsKeyword */) {
- var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1);
- return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node);
- }
+ if (node.token === 109 /* ImplementsKeyword */) {
+ // implements clauses are elided
return undefined;
}
+ return ts.visitEachChild(node, visitor, context);
+ }
/**
* Transforms an ExpressionWithTypeArguments with TypeScript syntax.
*
@@ -68138,16 +69155,6 @@
}
return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context));
}
- /**
- * Visits a method declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is an overload
- * - The node is marked as abstract, public, private, protected, or readonly
- * - The node has a computed property name
- *
- * @param node The method node.
- */
function visitMethodDeclaration(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return undefined;
@@ -68174,15 +69181,6 @@
function shouldEmitAccessorDeclaration(node) {
return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));
}
- /**
- * Visits a get accessor declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked as abstract, public, private, or protected
- * - The node has a computed property name
- *
- * @param node The get accessor node.
- */
function visitGetAccessor(node) {
if (!shouldEmitAccessorDeclaration(node)) {
return undefined;
@@ -68198,15 +69196,6 @@
}
return updated;
}
- /**
- * Visits a set accessor declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked as abstract, public, private, or protected
- * - The node has a computed property name
- *
- * @param node The set accessor node.
- */
function visitSetAccessor(node) {
if (!shouldEmitAccessorDeclaration(node)) {
return undefined;
@@ -68221,16 +69210,6 @@
}
return updated;
}
- /**
- * Visits a function declaration.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is an overload
- * - The node is exported from a TypeScript namespace
- * - The node has decorators
- *
- * @param node The function node.
- */
function visitFunctionDeclaration(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return ts.createNotEmittedStatement(node);
@@ -68246,14 +69225,6 @@
}
return updated;
}
- /**
- * Visits a function expression node.
- *
- * This function will be called when one of the following conditions are met:
- * - The node has type annotations
- *
- * @param node The function expression node.
- */
function visitFunctionExpression(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return ts.createOmittedExpression();
@@ -68263,51 +69234,31 @@
/*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
return updated;
}
- /**
- * @remarks
- * This function will be called when one of the following conditions are met:
- * - The node has type annotations
- */
function visitArrowFunction(node) {
var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier),
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
/*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
return updated;
}
- /**
- * Visits a parameter declaration node.
- *
- * This function will be called when one of the following conditions are met:
- * - The node has an accessibility modifier.
- * - The node has a questionToken.
- * - The node's kind is ThisKeyword.
- *
- * @param node The parameter declaration node.
- */
function visitParameter(node) {
if (ts.parameterIsThisKeyword(node)) {
return undefined;
}
- var parameter = ts.createParameter(
+ var updated = ts.updateParameter(node,
/*decorators*/ undefined,
/*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName),
/*questionToken*/ undefined,
/*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
+ if (updated !== node) {
// While we emit the source map for the node after skipping decorators and modifiers,
// we need to emit the comments for the original range.
- ts.setOriginalNode(parameter, node);
- ts.setTextRange(parameter, ts.moveRangePastModifiers(node));
- ts.setCommentRange(parameter, node);
- ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node));
- ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */);
- return parameter;
+ ts.setCommentRange(updated, node);
+ ts.setTextRange(updated, ts.moveRangePastModifiers(node));
+ ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
+ ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
+ }
+ return updated;
}
- /**
- * Visits a variable statement in a namespace.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is exported from a TypeScript namespace.
- */
function visitVariableStatement(node) {
if (isExportOfNamespace(node)) {
var variables = ts.getInitializedVariables(node.declarationList);
@@ -68336,12 +69287,6 @@
return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName),
/*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
}
- /**
- * Visits a parenthesized expression that contains either a type assertion or an `as`
- * expression.
- *
- * @param node The parenthesized expression node.
- */
function visitParenthesizedExpression(node) {
var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */);
if (ts.isAssertionExpression(innerExpression)) {
@@ -68478,7 +69423,7 @@
var statements = [];
startLexicalEnvironment();
var members = ts.map(node.members, transformEnumMember);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
ts.addRange(statements, members);
currentNamespaceContainerName = savedCurrentNamespaceLocalName;
return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members),
@@ -68577,7 +69522,7 @@
// 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))
- ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
+ ], currentLexicalScope.kind === 284 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
ts.setOriginalNode(statement, node);
recordEmittedDeclarationInScope(node);
if (isFirstEmittedDeclarationInScope(node)) {
@@ -68725,7 +69670,7 @@
var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
currentNamespaceContainerName = savedCurrentNamespaceContainerName;
currentNamespace = savedCurrentNamespace;
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
@@ -69142,7 +70087,7 @@
// 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 !== 279 /* SourceFile */) {
+ if (container && container.kind !== 284 /* SourceFile */) {
var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) ||
(applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */);
if (substitute) {
@@ -69193,39 +70138,39 @@
argumentsArray.push(descriptor);
}
}
- context.requestEmitHelper(decorateHelper);
+ context.requestEmitHelper(ts.decorateHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"),
/*typeArguments*/ undefined, argumentsArray), location);
}
- var decorateHelper = {
+ ts.decorateHelper = {
name: "typescript:decorate",
scoped: false,
priority: 2,
text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
};
function createMetadataHelper(context, metadataKey, metadataValue) {
- context.requestEmitHelper(metadataHelper);
+ context.requestEmitHelper(ts.metadataHelper);
return ts.createCall(ts.getHelperName("__metadata"),
/*typeArguments*/ undefined, [
ts.createLiteral(metadataKey),
metadataValue
]);
}
- var metadataHelper = {
+ ts.metadataHelper = {
name: "typescript:metadata",
scoped: false,
priority: 3,
text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
};
function createParamHelper(context, expression, parameterOffset, location) {
- context.requestEmitHelper(paramHelper);
+ context.requestEmitHelper(ts.paramHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__param"),
/*typeArguments*/ undefined, [
ts.createLiteral(parameterOffset),
expression
]), location);
}
- var paramHelper = {
+ ts.paramHelper = {
name: "typescript:param",
scoped: false,
priority: 4,
@@ -69280,7 +70225,7 @@
return visited;
}
function visitor(node) {
- if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) {
+ if ((node.transformFlags & 32 /* ContainsES2017 */) === 0) {
return node;
}
switch (node.kind) {
@@ -69550,22 +70495,26 @@
}
var savedCapturedSuperProperties = capturedSuperProperties;
var savedHasSuperElementAccess = hasSuperElementAccess;
+ if (!isArrowFunction) {
capturedSuperProperties = ts.createUnderscoreEscapedMap();
hasSuperElementAccess = false;
+ }
var result;
if (!isArrowFunction) {
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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
if (emitSuperHelpers) {
enableSubstitutionForAsyncMethodsWithSuper();
+ if (ts.hasEntries(capturedSuperProperties)) {
var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
- ts.addStatementsAfterPrologue(statements, [variableStatement]);
+ ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
+ }
}
var block = ts.createBlock(statements, /*multiLine*/ true);
ts.setTextRange(block, node.body);
@@ -69592,8 +70541,10 @@
}
}
enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
+ if (!isArrowFunction) {
capturedSuperProperties = savedCapturedSuperProperties;
hasSuperElementAccess = savedHasSuperElementAccess;
+ }
return result;
}
function transformAsyncFunctionBodyWorker(body, start) {
@@ -69746,7 +70697,7 @@
/* typeParameters */ undefined,
/* parameters */ [],
/* type */ undefined,
- /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name))));
+ /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
if (hasBinding) {
getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(
/* modifiers */ undefined,
@@ -69761,7 +70712,7 @@
/* initializer */ undefined)
],
/* type */ undefined,
- /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v")))));
+ /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v")))));
}
accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter)));
});
@@ -69776,14 +70727,14 @@
], 2 /* Const */));
}
ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
- var awaiterHelper = {
+ ts.awaiterHelper = {
name: "typescript:awaiter",
scoped: false,
priority: 5,
text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
};
function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
- context.requestEmitHelper(awaiterHelper);
+ context.requestEmitHelper(ts.awaiterHelper);
var generatorFunc = ts.createFunctionExpression(
/*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */),
/*name*/ undefined,
@@ -69819,7 +70770,7 @@
/** Enables substitutions for async methods with `super` calls. */
ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
})(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
- function transformESNext(context) {
+ function transformES2018(context) {
var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
var resolver = context.getEmitResolver();
var compilerOptions = context.getCompilerOptions();
@@ -69859,7 +70810,7 @@
return node;
}
function visitorWorker(node, noDestructuringValue) {
- if ((node.transformFlags & 8 /* ContainsESNext */) === 0) {
+ if ((node.transformFlags & 16 /* ContainsES2018 */) === 0) {
return node;
}
switch (node.kind) {
@@ -69903,8 +70854,6 @@
return visitExpressionStatement(node);
case 195 /* ParenthesizedExpression */:
return visitParenthesizedExpression(node, noDestructuringValue);
- case 274 /* CatchClause */:
- return visitCatchClause(node);
case 189 /* PropertyAccessExpression */:
if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) {
capturedSuperProperties.set(node.name.escapedText, true);
@@ -69979,7 +70928,7 @@
return objects;
}
function visitObjectLiteralExpression(node) {
- if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
// spread elements emit like so:
// non-spread elements are chunked together into object literals, and then all are passed to __assign:
// { a, ...o, b } => __assign({a}, o, {b});
@@ -69999,19 +70948,13 @@
function visitParenthesizedExpression(node, noDestructuringValue) {
return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
}
- function visitCatchClause(node) {
- if (!node.variableDeclaration) {
- return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
- }
- return ts.visitEachChild(node, visitor, context);
- }
/**
* Visits a BinaryExpression that contains a destructuring assignment.
*
* @param node A BinaryExpression node.
*/
function visitBinaryExpression(node, noDestructuringValue) {
- if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
}
else if (node.operatorToken.kind === 27 /* CommaToken */) {
@@ -70026,7 +70969,7 @@
*/
function visitVariableDeclaration(node) {
// If we are here it is because the name contains a binding pattern with a rest somewhere in it.
- if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (ts.isBindingPattern(node.name) && node.name.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */);
}
return ts.visitEachChild(node, visitor, context);
@@ -70043,7 +70986,7 @@
* @param node A ForOfStatement.
*/
function visitForOfStatement(node, outermostLabeledStatement) {
- if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.initializer.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
node = transformForOfStatementWithObjectRest(node);
}
if (node.awaitModifier) {
@@ -70140,7 +71083,7 @@
]));
}
function visitParameter(node) {
- if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
// Binding patterns are converted into a generated name and are
// evaluated inside the function body.
return ts.updateParameter(node,
@@ -70253,10 +71196,10 @@
enableSubstitutionForAsyncMethodsWithSuper();
var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
- ts.addStatementsAfterPrologue(statements, [variableStatement]);
+ ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
}
statements.push(returnStatement);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var block = ts.updateBlock(node.body, statements);
if (emitSuperHelpers && hasSuperElementAccess) {
if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
@@ -70282,7 +71225,7 @@
var leadingStatements = endLexicalEnvironment();
if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
- ts.addStatementsAfterPrologue(statements, leadingStatements);
+ ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
ts.addRange(statements, block.statements.slice(statementOffset));
return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
}
@@ -70291,7 +71234,7 @@
function appendObjectRestAssignmentsIfNeeded(statements, node) {
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
- if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (parameter.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
var temp = ts.getGeneratedNameForNode(parameter);
var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp,
/*doNotRecordTempVariablesInLine*/ false,
@@ -70422,8 +71365,8 @@
}
}
}
- ts.transformESNext = transformESNext;
- var assignHelper = {
+ ts.transformES2018 = transformES2018;
+ ts.assignHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
@@ -70434,28 +71377,28 @@
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"),
/*typeArguments*/ undefined, attributesSegments);
}
- context.requestEmitHelper(assignHelper);
+ context.requestEmitHelper(ts.assignHelper);
return ts.createCall(ts.getHelperName("__assign"),
/*typeArguments*/ undefined, attributesSegments);
}
ts.createAssignHelper = createAssignHelper;
- var awaitHelper = {
+ ts.awaitHelper = {
name: "typescript:await",
scoped: false,
text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
};
function createAwaitHelper(context, expression) {
- context.requestEmitHelper(awaitHelper);
+ context.requestEmitHelper(ts.awaitHelper);
return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
}
- var asyncGeneratorHelper = {
+ ts.asyncGeneratorHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
};
function createAsyncGeneratorHelper(context, generatorFunc) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncGeneratorHelper);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncGeneratorHelper);
// Mark this node as originally an async function
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */;
return ts.createCall(ts.getHelperName("__asyncGenerator"),
@@ -70465,24 +71408,24 @@
generatorFunc
]);
}
- var asyncDelegator = {
+ ts.asyncDelegator = {
name: "typescript:asyncDelegator",
scoped: false,
text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
};
function createAsyncDelegatorHelper(context, expression, location) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncDelegator);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncDelegator);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"),
/*typeArguments*/ undefined, [expression]), location);
}
- var asyncValues = {
+ ts.asyncValues = {
name: "typescript:asyncValues",
scoped: false,
text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
};
function createAsyncValuesHelper(context, expression, location) {
- context.requestEmitHelper(asyncValues);
+ context.requestEmitHelper(ts.asyncValues);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"),
/*typeArguments*/ undefined, [expression]), location);
}
@@ -70490,6 +71433,60 @@
/*@internal*/
var ts;
(function (ts) {
+ function transformES2019(context) {
+ return ts.chainBundle(transformSourceFile);
+ function transformSourceFile(node) {
+ if (node.isDeclarationFile) {
+ return node;
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitor(node) {
+ if ((node.transformFlags & 8 /* ContainsES2019 */) === 0) {
+ return node;
+ }
+ switch (node.kind) {
+ case 274 /* CatchClause */:
+ return visitCatchClause(node);
+ default:
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ function visitCatchClause(node) {
+ if (!node.variableDeclaration) {
+ return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ ts.transformES2019 = transformES2019;
+})(ts || (ts = {}));
+/*@internal*/
+var ts;
+(function (ts) {
+ function transformESNext(context) {
+ return ts.chainBundle(transformSourceFile);
+ function transformSourceFile(node) {
+ if (node.isDeclarationFile) {
+ return node;
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitor(node) {
+ if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
+ return node;
+ }
+ switch (node.kind) {
+ default:
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ }
+ ts.transformESNext = transformESNext;
+})(ts || (ts = {}));
+/*@internal*/
+var ts;
+(function (ts) {
function transformJsx(context) {
var compilerOptions = context.getCompilerOptions();
var currentSourceFile;
@@ -70509,7 +71506,7 @@
return visited;
}
function visitor(node) {
- if (node.transformFlags & 4 /* ContainsJsx */) {
+ if (node.transformFlags & 2 /* ContainsJsx */) {
return visitorWorker(node);
}
else {
@@ -70626,7 +71623,7 @@
}
}
function visitJsxText(node) {
- var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, /*includeTrivia*/ true));
+ var fixed = fixupWhitespaceAndDecodeEntities(node.text);
return fixed === undefined ? undefined : ts.createLiteral(fixed);
}
/**
@@ -71011,7 +72008,7 @@
return ts.visitEachChild(node, visitor, context);
}
function visitor(node) {
- if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) {
+ if ((node.transformFlags & 64 /* ContainsES2016 */) === 0) {
return node;
}
switch (node.kind) {
@@ -71091,30 +72088,6 @@
Jump[Jump["Continue"] = 4] = "Continue";
Jump[Jump["Return"] = 8] = "Return";
})(Jump || (Jump = {}));
- var SuperCaptureResult;
- (function (SuperCaptureResult) {
- /**
- * A capture may have been added for calls to 'super', but
- * the caller should emit subsequent statements normally.
- */
- SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement";
- /**
- * A call to 'super()' got replaced with a capturing statement like:
- *
- * var _this = _super.call(...) || this;
- *
- * Callers should skip the current statement.
- */
- SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture";
- /**
- * A call to 'super()' got replaced with a capturing statement like:
- *
- * return _super.call(...) || this;
- *
- * Callers should skip the current statement and avoid any returns of '_this'.
- */
- SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn";
- })(SuperCaptureResult || (SuperCaptureResult = {}));
// Facts we track as we traverse the tree
var HierarchyFacts;
(function (HierarchyFacts) {
@@ -71135,12 +72108,12 @@
HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement";
HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement";
HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper";
- HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName";
// NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
+ // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
//
// Ancestor masks
//
- HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
+ HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 8191] = "AncestorFactsMask";
// We are always in *some* kind of block scope, but only specific block-scope containers are
// top-level or Blocks.
HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
@@ -71150,16 +72123,16 @@
HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes";
// Functions, methods, and accessors are both new lexical scopes and new block scopes.
HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
- HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
+ HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 8094] = "FunctionExcludes";
HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
- HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
+ HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 8086] = "AsyncFunctionBodyExcludes";
// Arrow functions are lexically scoped to their container, but are new block scopes.
HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
- HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes";
+ HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 8064] = "ArrowFunctionExcludes";
// Constructors are both new lexical scopes and new block scopes. Constructors are also
// always considered non-static members of a class.
HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
- HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
+ HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 8086] = "ConstructorExcludes";
// 'do' and 'while' statements are not block scopes. We track that the subtree is contained
// within an IterationStatement to indicate whether the embedded statement is an
// IterationStatementBlock.
@@ -71177,19 +72150,17 @@
HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes";
HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes";
- // Computed property names track subtree flags differently than their containing members.
- HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes";
- HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes";
//
// Subtree facts
//
- HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
- HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName";
+ HierarchyFacts[HierarchyFacts["NewTarget"] = 8192] = "NewTarget";
+ HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 16384] = "CapturedLexicalThis";
//
// Subtree masks
//
- HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
- HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask";
+ HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -8192] = "SubtreeFactsMask";
+ HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
+ HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 24576] = "FunctionSubtreeExcludes";
})(HierarchyFacts || (HierarchyFacts = {}));
function transformES2015(context) {
var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
@@ -71238,7 +72209,7 @@
*/
function enterSubtree(excludeFacts, includeFacts) {
var ancestorFacts = hierarchyFacts;
- hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 8191 /* AncestorFactsMask */;
return ancestorFacts;
}
/**
@@ -71249,7 +72220,7 @@
* @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
*/
function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
- hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -8192 /* SubtreeFactsMask */ | ancestorFacts;
}
function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0
@@ -71271,12 +72242,6 @@
return node;
}
}
- function functionBodyVisitor(node) {
- if (shouldVisitNode(node)) {
- return visitBlock(node, /*isFunctionBody*/ true);
- }
- return node;
- }
function callExpressionVisitor(node) {
if (node.kind === 98 /* SuperKeyword */) {
return visitSuperKeyword(/*isExpressionOfCall*/ true);
@@ -71383,18 +72348,19 @@
}
function visitSourceFile(node) {
var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
+ var prologue = [];
var statements = [];
startLexicalEnvironment();
- var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false);
- addCaptureThisForNodeIfNeeded(statements, node);
- statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor);
+ var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false);
+ statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor);
ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
if (taggedTemplateStringDeclarations) {
statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureThisForNodeIfNeeded(prologue, node);
exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
- return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
+ return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
}
function visitSwitchStatement(node) {
if (convertedLoopState !== undefined) {
@@ -71434,6 +72400,9 @@
return ts.visitEachChild(node, visitor, context);
}
function visitThisKeyword(node) {
+ if (hierarchyFacts & 2 /* ArrowFunction */) {
+ hierarchyFacts |= 16384 /* CapturedLexicalThis */;
+ }
if (convertedLoopState) {
if (hierarchyFacts & 2 /* ArrowFunction */) {
// if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
@@ -71647,7 +72616,7 @@
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
ts.setEmitFlags(block, 1536 /* NoComments */);
return block;
@@ -71675,7 +72644,7 @@
function addConstructor(statements, node, extendsClauseElement) {
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
+ var ancestorFacts = enterSubtree(8086 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
var constructor = ts.getFirstConstructorWithBody(node);
var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
var constructorFunction = ts.createFunctionDeclaration(
@@ -71689,7 +72658,7 @@
ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
}
statements.push(constructorFunction);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
}
/**
@@ -71708,6 +72677,24 @@
return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
|| [];
}
+ function createDefaultConstructorBody(node, isDerivedClass) {
+ // We must be here because the user didn't write a constructor
+ // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
+ // If that's the case we can just immediately return the result of a 'super()' call.
+ var statements = [];
+ resumeLexicalEnvironment();
+ ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
+ if (isDerivedClass) {
+ // return _super !== null && _super.apply(this, arguments) || this;
+ statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
+ }
+ var statementsArray = ts.createNodeArray(statements);
+ ts.setTextRange(statementsArray, node.members);
+ var block = ts.createBlock(statementsArray, /*multiLine*/ true);
+ ts.setTextRange(block, node);
+ ts.setEmitFlags(block, 1536 /* NoComments */);
+ return block;
+ }
/**
* Transforms the body of a constructor declaration of a class.
*
@@ -71718,59 +72705,137 @@
* synthesized `super` call.
*/
function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
+ // determine whether the class is known syntactically to be a derived class (e.g. a
+ // class that extends a value that is not syntactically known to be `null`).
+ var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */;
+ // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
+ // representation:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base { }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // return _super.apply(this, arguments) || this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ if (!constructor)
+ return createDefaultConstructorBody(node, isDerivedClass);
+ // The prologue will contain all leading standard and custom prologue statements added by this transform
+ var prologue = [];
var statements = [];
resumeLexicalEnvironment();
- var statementOffset = -1;
- if (hasSynthesizedSuper) {
// If a super call has already been synthesized,
// we're going to assume that we should just transform everything after that.
// The assumption is that no prior step in the pipeline has added any prologue directives.
- statementOffset = 0;
- }
- else if (constructor) {
- statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false);
- }
- if (constructor) {
+ var statementOffset = 0;
+ if (!hasSynthesizedSuper)
+ statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false);
addDefaultValueAssignmentsIfNeeded(statements, constructor);
addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
- if (!hasSynthesizedSuper) {
- // If no super call has been synthesized, emit custom prologue directives.
+ if (!hasSynthesizedSuper)
statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
+ // If the first statement is a call to `super()`, visit the statement directly
+ var superCallExpression;
+ if (hasSynthesizedSuper) {
+ superCallExpression = createDefaultSuperCallOrThis();
}
- ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!");
+ else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
+ var firstStatement = constructor.body.statements[statementOffset];
+ if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
+ superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
}
- // determine whether the class is known syntactically to be a derived class (e.g. a
- // class that extends a value that is not syntactically known to be `null`).
- var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */;
- var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset);
- // The last statement expression was replaced. Skip it.
- if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) {
- statementOffset++;
}
- if (constructor) {
- if (superCaptureStatus === 1 /* ReplaceSuperCapture */) {
+ if (superCallExpression) {
hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */;
+ statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
}
+ // visit the remaining statements
ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
+ if (isDerivedClass) {
+ if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 2048 /* ContainsLexicalThis */)) {
+ // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
+ // following representation:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base {
+ // constructor() {
+ // super("foo");
+ // }
+ // }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // return _super.call(this, "foo") || this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
+ var returnStatement = ts.createReturn(superCallExpression);
+ ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
+ ts.setEmitFlags(superCall, 1536 /* NoComments */);
+ statements.push(returnStatement);
}
- // Return `_this` unless we're sure enough that it would be pointless to add a return statement.
- // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return.
- if (isDerivedClass
- && superCaptureStatus !== 2 /* ReplaceWithReturn */
- && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) {
+ else {
+ // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base {
+ // constructor() {
+ // super("foo");
+ // this.x = 1;
+ // }
+ // }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // var _this = _super.call(this, "foo") || this;
+ // _this.x = 1;
+ // return _this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ // Since the `super()` call was the first statement, we insert the `this` capturing call to
+ // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
+ insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
+ if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
- if (constructor) {
- prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false);
}
- var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements),
- /*location*/ constructor ? constructor.body.statements : node.members),
- /*multiLine*/ true);
- ts.setTextRange(block, constructor ? constructor.body : node);
- if (!constructor) {
- ts.setEmitFlags(block, 1536 /* NoComments */);
}
+ else {
+ // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
+ // captured when necessitated by an arrow function capturing the lexical `this`:
+ //
+ // ```
+ // // es2015
+ // class C {}
+ //
+ // // es5
+ // var C = (function () {
+ // function C() {
+ // }
+ // return C;
+ // })();
+ // ```
+ insertCaptureThisForNodeIfNeeded(prologue, constructor);
+ }
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)),
+ /*location*/ constructor.body.statements),
+ /*multiLine*/ true);
+ ts.setTextRange(block, constructor.body);
return block;
}
/**
@@ -71800,83 +72865,6 @@
}
return false;
}
- /**
- * Declares a `_this` variable for derived classes and for when arrow functions capture `this`.
- *
- * @returns The new statement offset into the `statements` array.
- */
- function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) {
- // If this isn't a derived class, just capture 'this' for arrow functions if necessary.
- if (!isDerivedClass) {
- if (ctor) {
- addCaptureThisForNodeIfNeeded(statements, ctor);
- }
- return 0 /* NoReplacement */;
- }
- // We must be here because the user didn't write a constructor
- // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
- // If that's the case we can just immediately return the result of a 'super()' call.
- if (!ctor) {
- statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
- return 2 /* ReplaceWithReturn */;
- }
- // The constructor exists, but it and the 'super()' call it contains were generated
- // for something like property initializers.
- // Create a captured '_this' variable and assume it will subsequently be used.
- if (hasSynthesizedSuper) {
- captureThisForNode(statements, ctor, createDefaultSuperCallOrThis());
- enableSubstitutionsForCapturedThis();
- return 1 /* ReplaceSuperCapture */;
- }
- // Most of the time, a 'super' call will be the first real statement in a constructor body.
- // In these cases, we'd like to transform these into a *single* statement instead of a declaration
- // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer,
- // we'd get:
- //
- // var _this;
- // _this = _super.call(...) || this;
- //
- // instead of
- //
- // var _this = _super.call(...) || this;
- //
- // Additionally, if the 'super()' call is the last statement, we should just avoid capturing
- // entirely and immediately return the result like so:
- //
- // return _super.call(...) || this;
- //
- var firstStatement;
- var superCallExpression;
- var ctorStatements = ctor.body.statements;
- if (statementOffset < ctorStatements.length) {
- firstStatement = ctorStatements[statementOffset];
- if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) {
- superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
- }
- }
- // Return the result if we have an immediate super() call on the last statement,
- // but only if the constructor itself doesn't use 'this' elsewhere.
- if (superCallExpression
- && statementOffset === ctorStatements.length - 1
- && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) {
- var returnStatement = ts.createReturn(superCallExpression);
- if (superCallExpression.kind !== 204 /* BinaryExpression */
- || superCallExpression.left.kind !== 191 /* 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.
- ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */)));
- statements.push(returnStatement);
- return 2 /* ReplaceWithReturn */;
- }
- // Perform the capture.
- 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 */;
- }
- return 0 /* NoReplacement */;
- }
function createActualThis() {
return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
}
@@ -71922,14 +72910,9 @@
return node;
}
}
- /**
- * Gets a value indicating whether we need to add default value assignments for a
- * function-like node.
- *
- * @param node A function-like node.
- */
- function shouldAddDefaultValueAssignments(node) {
- return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0;
+ function hasDefaultValueOrBindingPattern(node) {
+ return node.initializer !== undefined
+ || ts.isBindingPattern(node.name);
}
/**
* Adds statements to the body of a function-like node if it contains parameters with
@@ -71939,9 +72922,10 @@
* @param node A function-like node.
*/
function addDefaultValueAssignmentsIfNeeded(statements, node) {
- if (!shouldAddDefaultValueAssignments(node)) {
- return;
+ if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
+ return false;
}
+ var added = false;
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
@@ -71951,12 +72935,14 @@
continue;
}
if (ts.isBindingPattern(name)) {
- addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer);
+ added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
}
else if (initializer) {
- addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
+ insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
+ added = true;
}
}
+ return added;
}
/**
* Adds statements to the body of a function-like node for parameters with binding patterns
@@ -71966,18 +72952,20 @@
* @param name The name of the parameter.
* @param initializer The initializer for the parameter.
*/
- function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
- var temp = ts.getGeneratedNameForNode(parameter);
+ function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
// In cases where a binding pattern is simply '[]' or '{}',
// we usually don't want to emit a var declaration; however, in the presence
// of an initializer, we must emit that expression to preserve side effects.
if (name.elements.length > 0) {
- statements.push(ts.setEmitFlags(ts.createVariableStatement(
- /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */));
+ ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(
+ /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
+ return true;
}
else if (initializer) {
- statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
+ ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
+ return true;
}
+ return false;
}
/**
* Adds statements to the body of a function-like node for parameters with initializers.
@@ -71987,7 +72975,7 @@
* @param name The name of the parameter.
* @param initializer The initializer for the parameter.
*/
- function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
+ function insertDefaultValueAssignmentForInitializer(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.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 */))
@@ -71995,7 +72983,7 @@
ts.startOnNewLine(statement);
ts.setTextRange(statement, parameter);
ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
- statements.push(statement);
+ ts.insertStatementAfterCustomPrologue(statements, statement);
}
/**
* Gets a value indicating whether we need to add statements to handle a rest parameter.
@@ -72018,9 +73006,10 @@
* synthesized call to `super`
*/
function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
+ var prologueStatements = [];
var parameter = ts.lastOrUndefined(node.parameters);
if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
- return;
+ return false;
}
// `declarationName` is the name of the local declaration for the parameter.
var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined);
@@ -72030,7 +73019,7 @@
var restIndex = node.parameters.length - 1;
var temp = ts.createLoopVariable();
// var param = [];
- statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
+ prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList([
ts.createVariableDeclaration(declarationName,
/*type*/ undefined, ts.createArrayLiteral([]))
@@ -72049,25 +73038,30 @@
]));
ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
ts.startOnNewLine(forStatement);
- statements.push(forStatement);
+ prologueStatements.push(forStatement);
if (parameter.name.kind !== 72 /* Identifier */) {
// do the actual destructuring of the rest parameter if necessary
- statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
+ prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
}
+ ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
+ return true;
}
/**
* Adds a statement to capture the `this` of a function declaration if it is needed.
+ * NOTE: This must be executed *after* the subtree has been visited.
*
* @param statements The statements for the new function body.
* @param node A node.
*/
- function addCaptureThisForNodeIfNeeded(statements, node) {
- if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) {
- captureThisForNode(statements, node, ts.createThis());
+ function insertCaptureThisForNodeIfNeeded(statements, node) {
+ if (hierarchyFacts & 16384 /* CapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) {
+ insertCaptureThisForNode(statements, node, ts.createThis());
+ return true;
}
+ return false;
}
- function captureThisForNode(statements, node, initializer) {
+ function insertCaptureThisForNode(statements, node, initializer) {
enableSubstitutionsForCapturedThis();
var captureThisStatement = ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList([
@@ -72076,10 +73070,10 @@
]));
ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
ts.setSourceMapRange(captureThisStatement, node);
- statements.push(captureThisStatement);
+ ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
}
- function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
- if (hierarchyFacts & 16384 /* NewTarget */) {
+ function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
+ if (hierarchyFacts & 8192 /* NewTarget */) {
var newTarget = void 0;
switch (node.kind) {
case 197 /* ArrowFunction */:
@@ -72110,10 +73104,11 @@
ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"),
/*type*/ undefined, newTarget)
]));
+ ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
if (copyOnWrite) {
- return [captureNewTargetStatement].concat(statements);
+ statements = statements.slice();
}
- statements.unshift(captureNewTargetStatement);
+ ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
}
return statements;
}
@@ -72165,7 +73160,6 @@
* @param member The MethodDeclaration node.
*/
function transformClassMethodDeclarationToStatement(receiver, member, container) {
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
var commentRange = ts.getCommentRange(member);
var sourceMapRange = ts.getSourceMapRange(member);
var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name);
@@ -72180,7 +73174,6 @@
// No source map should be emitted for this statement to align with the
// old emitter.
ts.setEmitFlags(statement, 48 /* NoSourceMap */);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return statement;
}
/**
@@ -72206,7 +73199,6 @@
*/
function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
// To align with source maps in the old emitter, the receiver and property name
// arguments are both mapped contiguously to the accessor name.
var target = ts.getMutableClone(receiver);
@@ -72242,7 +73234,6 @@
if (startsOnNewLine) {
ts.startOnNewLine(call);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return call;
}
/**
@@ -72251,12 +73242,12 @@
* @param node An ArrowFunction node.
*/
function visitArrowFunction(node) {
- if (node.transformFlags & 8192 /* ContainsLexicalThis */) {
- enableSubstitutionsForCapturedThis();
+ if (node.transformFlags & 2048 /* ContainsLexicalThis */) {
+ hierarchyFacts |= 16384 /* CapturedLexicalThis */;
}
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
+ var ancestorFacts = enterSubtree(8064 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
var func = ts.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
@@ -72266,7 +73257,11 @@
ts.setTextRange(func, node);
ts.setOriginalNode(func, node);
ts.setEmitFlags(func, 8 /* CapturesThis */);
- exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
+ if (hierarchyFacts & 16384 /* CapturedLexicalThis */) {
+ enableSubstitutionsForCapturedThis();
+ }
+ // If an arrow function contains
+ exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return func;
}
@@ -72277,18 +73272,16 @@
*/
function visitFunctionExpression(node) {
var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
- ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
- : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ ? enterSubtree(8086 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
+ : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & 64 /* ES2015 */
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
- var name = hierarchyFacts & 16384 /* NewTarget */
+ var body = transformFunctionBody(node);
+ var name = hierarchyFacts & 8192 /* NewTarget */
? ts.getLocalName(node)
: node.name;
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.updateFunctionExpression(node,
/*modifiers*/ undefined, node.asteriskToken, name,
@@ -72303,15 +73296,13 @@
function visitFunctionDeclaration(node) {
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & 64 /* ES2015 */
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
- var name = hierarchyFacts & 16384 /* NewTarget */
+ var body = transformFunctionBody(node);
+ var name = hierarchyFacts & 8192 /* NewTarget */
? ts.getLocalName(node)
: node.name;
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.updateFunctionDeclaration(node,
/*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name,
@@ -72329,14 +73320,14 @@
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
- ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
- : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ ? enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
+ : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var parameters = ts.visitParameterList(node.parameters, visitor, context);
var body = transformFunctionBody(node);
- if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) {
+ if (hierarchyFacts & 8192 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) {
name = ts.getGeneratedNameForNode(node);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
/*modifiers*/ undefined, node.asteriskToken, name,
@@ -72354,7 +73345,7 @@
var singleLine = false; // indicates whether the block *may* be emitted as a single line
var statementsLocation;
var closeBraceLocation;
- var leadingStatements = [];
+ var prologue = [];
var statements = [];
var body = node.body;
var statementOffset;
@@ -72362,14 +73353,13 @@
if (ts.isBlock(body)) {
// ensureUseStrict is false because no new prologue-directive should be added.
// addStandardPrologue will put already-existing directives at the beginning of the target statement-array
- statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false);
+ statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false);
}
- addCaptureThisForNodeIfNeeded(leadingStatements, node);
- addDefaultValueAssignmentsIfNeeded(leadingStatements, node);
- addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false);
+ multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
+ multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
if (ts.isBlock(body)) {
// addCustomPrologue puts already-existing directives at the beginning of the target statement-array
- statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor);
+ statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
statementsLocation = body.statements;
ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
// If the original body was a multi-line block, this must be a multi-line block.
@@ -72403,14 +73393,19 @@
// source map location for the close brace.
closeBraceLocation = body;
}
- var lexicalEnvironment = context.endLexicalEnvironment();
- ts.addStatementsAfterPrologue(statements, lexicalEnvironment);
- prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false);
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
+ insertCaptureThisForNodeIfNeeded(prologue, node);
// If we added any final generated statements, this must be a multi-line block
- if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) {
+ if (ts.some(prologue)) {
multiLine = true;
}
- var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine);
+ statements.unshift.apply(statements, prologue);
+ if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
+ // no changes were made, preserve the tree
+ return body;
+ }
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
ts.setTextRange(block, node.body);
if (!multiLine && singleLine) {
ts.setEmitFlags(block, 1 /* SingleLine */);
@@ -72421,11 +73416,6 @@
ts.setOriginalNode(block, node.body);
return block;
}
- function visitFunctionBodyDownLevel(node) {
- var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context);
- return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)),
- /*location*/ updated.statements));
- }
function visitBlock(node, isFunctionBody) {
if (isFunctionBody) {
// A function body is not a block scope.
@@ -72530,7 +73520,7 @@
* @param node A VariableDeclarationList node.
*/
function visitVariableDeclarationList(node) {
- if (node.transformFlags & 64 /* ES2015 */) {
+ if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 65536 /* ContainsBindingPattern */) {
if (node.flags & 3 /* BlockScoped */) {
enableSubstitutionsForBlockScopedBindings();
}
@@ -72543,7 +73533,7 @@
ts.setCommentRange(declarationList, node);
// If the first or last declaration is a binding pattern, we need to modify
// the source map range for the declaration list.
- if (node.transformFlags & 2097152 /* ContainsBindingPattern */
+ if (node.transformFlags & 65536 /* ContainsBindingPattern */
&& (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
}
@@ -72865,7 +73855,7 @@
var numInitialPropertiesWithoutYield = numProperties;
for (var i = 0; i < numProperties; i++) {
var property = properties[i];
- if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
+ if ((property.transformFlags & 131072 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
&& i < numInitialPropertiesWithoutYield) {
numInitialPropertiesWithoutYield = i;
}
@@ -73141,7 +74131,7 @@
*/
function createFunctionForInitializerOfForStatement(node, currentState) {
var functionName = ts.createUniqueName("_loop_init");
- var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ var containsYield = (node.initializer.transformFlags & 131072 /* ContainsYield */) !== 0;
var emitFlags = 0 /* None */;
if (currentState.containsLexicalThis)
emitFlags |= 8 /* CapturesThis */;
@@ -73246,11 +74236,11 @@
statements.push(statement);
}
copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
- ts.addStatementsAfterPrologue(statements, lexicalEnvironment);
+ ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
var loopBody = ts.createBlock(statements, /*multiLine*/ true);
if (ts.isBlock(statement))
ts.setOriginalNode(loopBody, statement);
- var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ var containsYield = (node.statement.transformFlags & 131072 /* ContainsYield */) !== 0;
var emitFlags = 0;
if (currentState.containsLexicalThis)
emitFlags |= 8 /* CapturesThis */;
@@ -73482,13 +74472,11 @@
* @param receiver The receiver for the assignment.
*/
function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
ts.setTextRange(expression, method);
if (startsOnNewLine) {
ts.startOnNewLine(expression);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return expression;
}
function visitCatchClause(node) {
@@ -73540,19 +74528,17 @@
ts.Debug.assert(!ts.isComputedPropertyName(node.name));
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var updated;
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */)
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
+ var body = transformFunctionBody(node);
if (node.kind === 158 /* GetAccessor */) {
updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
}
else {
updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return updated;
}
@@ -73566,10 +74552,7 @@
/*location*/ node);
}
function visitComputedPropertyName(node) {
- var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */);
- var updated = ts.visitEachChild(node, visitor, context);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */);
- return updated;
+ return ts.visitEachChild(node, visitor, context);
}
/**
* Visits a YieldExpression node.
@@ -73586,7 +74569,7 @@
* @param node An ArrayLiteralExpression node.
*/
function visitArrayLiteralExpression(node) {
- if (node.transformFlags & 64 /* ES2015 */) {
+ if (ts.some(node.elements, ts.isSpreadElement)) {
// We are here because we contain a SpreadElementExpression.
return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
}
@@ -73601,7 +74584,10 @@
if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
return visitTypeScriptClassWrapper(node);
}
- if (node.transformFlags & 64 /* ES2015 */) {
+ var expression = ts.skipOuterExpressions(node.expression);
+ if (expression.kind === 98 /* SuperKeyword */ ||
+ ts.isSuperProperty(expression) ||
+ ts.some(node.arguments, ts.isSpreadElement)) {
return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
}
return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression),
@@ -73722,7 +74708,7 @@
function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
// We are here either because SuperKeyword was used somewhere in the expression, or
// because we contain a SpreadElementExpression.
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */ ||
+ if (node.transformFlags & 4096 /* ContainsRestOrSpread */ ||
node.expression.kind === 98 /* SuperKeyword */ ||
ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
@@ -73730,7 +74716,7 @@
ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
}
var resultingCall = void 0;
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */) {
+ if (node.transformFlags & 4096 /* ContainsRestOrSpread */) {
// [source]
// f(...a, b)
// x.m(...a, b)
@@ -73744,7 +74730,7 @@
// _super.apply(this, a.concat([b]))
// _super.m.apply(this, a.concat([b]))
// _super.prototype.m.apply(this, a.concat([b]))
- resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
+ resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
}
else {
// [source]
@@ -73756,13 +74742,11 @@
// _super.call(this, a)
// _super.m.call(this, a)
// _super.prototype.m.call(this, a)
- resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
+ resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
/*location*/ node);
}
if (node.expression.kind === 98 /* SuperKeyword */) {
- var actualThis = ts.createThis();
- ts.setEmitFlags(actualThis, 4 /* NoSubstitution */);
- var initializer = ts.createLogicalOr(resultingCall, actualThis);
+ var initializer = ts.createLogicalOr(resultingCall, createActualThis());
resultingCall = assignToCapturedThis
? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
: initializer;
@@ -73777,7 +74761,7 @@
* @param node A NewExpression node.
*/
function visitNewExpression(node) {
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */) {
+ if (ts.some(node.arguments, ts.isSpreadElement)) {
// We are here because we contain a SpreadElementExpression.
// [source]
// new C(...a)
@@ -74040,12 +75024,7 @@
}
function visitMetaProperty(node) {
if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") {
- if (hierarchyFacts & 8192 /* ComputedPropertyName */) {
- hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */;
- }
- else {
- hierarchyFacts |= 16384 /* NewTarget */;
- }
+ hierarchyFacts |= 8192 /* NewTarget */;
return ts.createFileLevelUniqueName("_newTarget");
}
return node;
@@ -74060,7 +75039,7 @@
function onEmitNode(hint, node, emitCallback) {
if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
// If we are tracking a captured `this`, keep track of the enclosing function.
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
: 65 /* FunctionIncludes */);
previousOnEmitNode(hint, node, emitCallback);
@@ -74240,7 +75219,7 @@
}
ts.transformES2015 = transformES2015;
function createExtendsHelper(context, name) {
- context.requestEmitHelper(extendsHelper);
+ context.requestEmitHelper(ts.extendsHelper);
return ts.createCall(ts.getHelperName("__extends"),
/*typeArguments*/ undefined, [
name,
@@ -74248,20 +75227,20 @@
]);
}
function createTemplateObjectHelper(context, cooked, raw) {
- context.requestEmitHelper(templateObjectHelper);
+ context.requestEmitHelper(ts.templateObjectHelper);
return ts.createCall(ts.getHelperName("__makeTemplateObject"),
/*typeArguments*/ undefined, [
cooked,
raw
]);
}
- var extendsHelper = {
+ ts.extendsHelper = {
name: "typescript:extends",
scoped: false,
priority: 0,
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 = {
+ ts.templateObjectHelper = {
name: "typescript:makeTemplateObject",
scoped: false,
priority: 0,
@@ -74608,7 +75587,7 @@
var withBlockStack; // A stack containing `with` blocks.
return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
- if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
+ if (node.isDeclarationFile || (node.transformFlags & 256 /* ContainsGenerator */) === 0) {
return node;
}
var visited = ts.visitEachChild(node, visitor, context);
@@ -74628,10 +75607,10 @@
else if (inGeneratorFunctionBody) {
return visitJavaScriptInGeneratorFunctionBody(node);
}
- else if (transformFlags & 256 /* Generator */) {
+ else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
return visitGenerator(node);
}
- else if (transformFlags & 512 /* ContainsGenerator */) {
+ else if (transformFlags & 256 /* ContainsGenerator */) {
return ts.visitEachChild(node, visitor, context);
}
else {
@@ -74684,10 +75663,10 @@
case 230 /* ReturnStatement */:
return visitReturnStatement(node);
default:
- if (node.transformFlags & 4194304 /* ContainsYield */) {
+ if (node.transformFlags & 131072 /* ContainsYield */) {
return visitJavaScriptContainingYield(node);
}
- else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) {
+ else if (node.transformFlags & (256 /* ContainsGenerator */ | 262144 /* ContainsHoistedDeclarationOrCompletion */)) {
return ts.visitEachChild(node, visitor, context);
}
else {
@@ -74863,7 +75842,7 @@
var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
transformAndEmitStatements(body.statements, statementOffset);
var buildResult = build();
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
statements.push(ts.createReturn(buildResult));
// Restore previous generator state
inGeneratorFunctionBody = savedInGeneratorFunctionBody;
@@ -74890,7 +75869,7 @@
* @param node The node to visit.
*/
function visitVariableStatement(node) {
- if (node.transformFlags & 4194304 /* ContainsYield */) {
+ if (node.transformFlags & 131072 /* ContainsYield */) {
transformAndEmitVariableDeclarationList(node.declarationList);
return undefined;
}
@@ -75948,7 +76927,7 @@
}
}
function containsYield(node) {
- return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ return !!node && (node.transformFlags & 131072 /* ContainsYield */) !== 0;
}
function countInitialNodesWithoutYield(nodes) {
var numNodes = nodes.length;
@@ -76955,7 +77934,7 @@
}
ts.transformGenerators = transformGenerators;
function createGeneratorHelper(context, body) {
- context.requestEmitHelper(generatorHelper);
+ context.requestEmitHelper(ts.generatorHelper);
return ts.createCall(ts.getHelperName("__generator"),
/*typeArguments*/ undefined, [ts.createThis(), body]);
}
@@ -77018,7 +77997,7 @@
// entering a finally block.
//
// For examples of how these are used, see the comments in ./transformers/generators.ts
- var generatorHelper = {
+ ts.generatorHelper = {
name: "typescript:generator",
scoped: false,
priority: 6,
@@ -77051,7 +78030,7 @@
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* 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.
@@ -77067,7 +78046,7 @@
function transformSourceFile(node) {
if (node.isDeclarationFile ||
!(ts.isEffectiveExternalModule(node, compilerOptions) ||
- node.transformFlags & 16777216 /* ContainsDynamicImport */ ||
+ node.transformFlags & 524288 /* ContainsDynamicImport */ ||
(ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
return node;
}
@@ -77104,7 +78083,7 @@
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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(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
@@ -77330,7 +78309,7 @@
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
// End the lexical environment for the module body
// and merge any new lexical declarations.
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var body = ts.createBlock(statements, /*multiLine*/ true);
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
// If we have any `export * from ...` declarations
@@ -77393,9 +78372,9 @@
return visitFunctionDeclaration(node);
case 240 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
@@ -77404,13 +78383,13 @@
function moduleExpressionElementVisitor(node) {
// This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
// as export/import statements are only transformed at the top level of a file.
- if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) {
+ if (!(node.transformFlags & 524288 /* ContainsDynamicImport */) && !(node.transformFlags & 512 /* ContainsDestructuringAssignment */)) {
return node;
}
if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
- else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) {
+ else if (ts.isDestructuringAssignment(node)) {
return visitDestructuringAssignment(node);
}
else {
@@ -77471,7 +78450,7 @@
}
function visitImportCallExpression(node) {
var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
- var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */);
+ var containsLexicalThis = !!(node.transformFlags & 2048 /* ContainsLexicalThis */);
switch (compilerOptions.module) {
case ts.ModuleKind.AMD:
return createImportCallExpressionAMD(argument, containsLexicalThis);
@@ -77553,7 +78532,7 @@
}
var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]);
}
return promise;
@@ -77567,7 +78546,7 @@
var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
}
var func;
@@ -77601,11 +78580,11 @@
return innerExpr;
}
if (ts.getImportNeedsImportStarHelper(node)) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
}
if (ts.getImportNeedsImportDefaultHelper(node)) {
- context.requestEmitHelper(importDefaultHelper);
+ context.requestEmitHelper(ts.importDefaultHelper);
return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
}
return innerExpr;
@@ -78174,7 +79153,7 @@
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
currentSourceFile = node;
currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
noSubstitution = [];
@@ -78262,7 +79241,7 @@
}
if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)),
/*location*/ node);
}
@@ -78388,13 +79367,13 @@
text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
};
// emit helper for `import * as Name from "foo"`
- var importStarHelper = {
+ ts.importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
// emit helper for `import Name from "foo"`
- var importDefaultHelper = {
+ ts.importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
@@ -78417,7 +79396,7 @@
context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols.
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* 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.
@@ -78436,7 +79415,7 @@
* @param node The SourceFile node.
*/
function transformSourceFile(node) {
- if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) {
+ if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 524288 /* ContainsDynamicImport */)) {
return node;
}
var id = ts.getOriginalNodeId(node);
@@ -78602,7 +79581,7 @@
// 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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
var moduleObject = ts.createObjectLiteral([
ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
@@ -78987,7 +79966,7 @@
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 === 279 /* SourceFile */
+ && (enclosingBlockScopedContainer.kind === 284 /* SourceFile */
|| (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
}
/**
@@ -79330,9 +80309,9 @@
return visitCatchClause(node);
case 218 /* Block */:
return visitBlock(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -79514,14 +80493,13 @@
* @param node The node to visit.
*/
function destructuringAndImportCallVisitor(node) {
- if (node.transformFlags & 1024 /* DestructuringAssignment */
- && node.kind === 204 /* BinaryExpression */) {
+ if (ts.isDestructuringAssignment(node)) {
return visitDestructuringAssignment(node);
}
else if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
- else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) {
+ else if ((node.transformFlags & 512 /* ContainsDestructuringAssignment */) || (node.transformFlags & 524288 /* ContainsDynamicImport */)) {
return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
}
else {
@@ -79580,7 +80558,7 @@
}
else if (ts.isIdentifier(node)) {
var container = resolver.getReferencedExportContainer(node);
- return container !== undefined && container.kind === 279 /* SourceFile */;
+ return container !== undefined && container.kind === 284 /* SourceFile */;
}
else {
return false;
@@ -79613,7 +80591,7 @@
* @param emitCallback A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
var id = ts.getOriginalNodeId(node);
currentSourceFile = node;
moduleInfo = moduleInfoMap[id];
@@ -79822,7 +80800,7 @@
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
}
exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
@@ -79861,7 +80839,7 @@
var previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- context.enableEmitNotification(279 /* SourceFile */);
+ context.enableEmitNotification(284 /* SourceFile */);
context.enableSubstitution(72 /* Identifier */);
var currentSourceFile;
return ts.chainBundle(transformSourceFile);
@@ -79971,7 +80949,8 @@
ts.isImportEqualsDeclaration(node) ||
ts.isTypeAliasDeclaration(node) ||
ts.isConstructorDeclaration(node) ||
- ts.isIndexSignatureDeclaration(node);
+ ts.isIndexSignatureDeclaration(node) ||
+ ts.isPropertyAccessExpression(node);
}
ts.canProduceDiagnostics = canProduceDiagnostics;
function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
@@ -80045,7 +81024,7 @@
}
ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
function createGetSymbolAccessibilityDiagnosticForNode(node) {
- if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
+ if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
return getVariableDeclarationTypeVisibilityError;
}
else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
@@ -80085,7 +81064,7 @@
}
// This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
// The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
- else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ ||
+ else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 189 /* PropertyAccessExpression */ || node.kind === 153 /* PropertySignature */ ||
(node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
// TODO(jfreeman): Deal with computed properties in error reporting.
if (ts.hasModifier(node, 32 /* Static */)) {
@@ -80290,6 +81269,9 @@
case 241 /* InterfaceDeclaration */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
break;
+ case 181 /* MappedType */:
+ diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
+ break;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
@@ -80373,6 +81355,31 @@
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
+ function hasInternalAnnotation(range, currentSourceFile) {
+ var comment = currentSourceFile.text.substring(range.pos, range.end);
+ return ts.stringContains(comment, "@internal");
+ }
+ function isInternalDeclaration(node, currentSourceFile) {
+ var parseTreeNode = ts.getParseTreeNode(node);
+ if (parseTreeNode && parseTreeNode.kind === 151 /* Parameter */) {
+ var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
+ var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
+ var text = currentSourceFile.text;
+ var commentRanges = previousSibling
+ ? ts.concatenate(
+ // to handle
+ // ... parameters, /* @internal */
+ // public param: string
+ ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
+ : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
+ return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
+ }
+ var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
+ return !!ts.forEach(leadingCommentRanges, function (range) {
+ return hasInternalAnnotation(range, currentSourceFile);
+ });
+ }
+ ts.isInternalDeclaration = isInternalDeclaration;
var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
2048 /* WriteClassExpressionAsTypeLiteral */ |
4096 /* UseTypeOfFunction */ |
@@ -80501,10 +81508,10 @@
}
}
function transformRoot(node) {
- if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
+ if (node.kind === 284 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
}
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
isBundledEmit = true;
refs = ts.createMap();
libs = ts.createMap();
@@ -80534,9 +81541,15 @@
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 === 282 /* InputFiles */) {
- return ts.createUnparsedSourceFile(prepend, "dts");
+ if (prepend.kind === 287 /* InputFiles */) {
+ var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
+ hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
+ collectReferences(sourceFile, refs);
+ recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
+ collectLibs(sourceFile, libs);
+ return sourceFile;
}
+ return prepend;
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -80628,7 +81641,7 @@
}
}
function collectReferences(sourceFile, ret) {
- if (noResolve || ts.isSourceFileJS(sourceFile))
+ if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
return ret;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
@@ -81175,7 +82188,9 @@
if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
return undefined;
}
+ getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker);
+ getSymbolAccessibilityDiagnostic = oldDiag;
var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
});
@@ -81218,7 +82233,7 @@
if (ctor) {
var oldDiag_1 = getSymbolAccessibilityDiagnostic;
parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
- if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */))
+ if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
return;
getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
if (param.name.kind === 72 /* Identifier */) {
@@ -81354,18 +82369,8 @@
}
errorNameNode = undefined;
}
- function hasInternalAnnotation(range) {
- var comment = currentSourceFile.text.substring(range.pos, range.end);
- return ts.stringContains(comment, "@internal");
- }
function shouldStripInternal(node) {
- if (stripInternal && node) {
- var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile);
- if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
- return true;
- }
- }
- return false;
+ return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
}
function isScopeMarker(node) {
return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
@@ -81387,7 +82392,7 @@
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 === 279 /* SourceFile */;
+ var parentIsFile = node.parent.kind === 284 /* SourceFile */;
if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */);
additions = 0 /* None */;
@@ -81556,9 +82561,15 @@
if (jsx === 2 /* React */) {
transformers.push(ts.transformJsx);
}
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
transformers.push(ts.transformESNext);
}
+ if (languageVersion < 6 /* ES2019 */) {
+ transformers.push(ts.transformES2019);
+ }
+ if (languageVersion < 5 /* ES2018 */) {
+ transformers.push(ts.transformES2018);
+ }
if (languageVersion < 4 /* ES2017 */) {
transformers.push(ts.transformES2017);
}
@@ -81598,7 +82609,7 @@
* @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(312 /* Count */);
+ var enabledSyntaxKindFeatures = new Array(317 /* Count */);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -81858,10 +82869,14 @@
})(ts || (ts = {}));
var ts;
(function (ts) {
- var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
var syntheticParent = { pos: -1, end: -1 };
/*@internal*/
+ function isBuildInfoFile(file) {
+ return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
+ }
+ ts.isBuildInfoFile = isBuildInfoFile;
+ /*@internal*/
/**
* Iterates over the source files that are expected to have an emit output.
*
@@ -81871,13 +82886,14 @@
* 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, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
+ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles, onlyBuildInfo, includeBuildInfo) {
if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; }
var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
+ var prepends = host.getPrependNodes();
+ if (sourceFiles.length || prepends.length) {
+ var bundle = ts.createBundle(sourceFiles, prepends);
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -81885,6 +82901,7 @@
}
}
else {
+ if (!onlyBuildInfo) {
for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
var sourceFile = sourceFiles_1[_a];
var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
@@ -81893,23 +82910,52 @@
}
}
}
+ if (includeBuildInfo) {
+ var buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
+ if (buildInfoPath)
+ return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
+ }
+ }
}
ts.forEachEmittedFile = forEachEmittedFile;
/*@internal*/
+ function getOutputPathForBuildInfo(options) {
+ var configFile = options.configFilePath;
+ if (!configFile || !ts.isIncrementalCompilation(options))
+ return undefined;
+ if (options.tsBuildInfoFile)
+ return options.tsBuildInfoFile;
+ var outPath = options.outFile || options.out;
+ var buildInfoExtensionLess;
+ if (outPath) {
+ buildInfoExtensionLess = ts.removeFileExtension(outPath);
+ }
+ else {
+ var configFileExtensionLess = ts.removeFileExtension(configFile);
+ buildInfoExtensionLess = options.outDir ?
+ options.rootDir ?
+ ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
+ ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
+ configFileExtensionLess;
+ }
+ return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
+ }
+ ts.getOutputPathForBuildInfo = getOutputPathForBuildInfo;
+ /*@internal*/
function getOutputPathsForBundle(options, forceDtsPaths) {
var outPath = options.outFile || options.out;
var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
var declarationMapPath = declarationFilePath && 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 };
+ var buildInfoPath = getOutputPathForBuildInfo(options);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
}
ts.getOutputPathsForBundle = getOutputPathsForBundle;
/*@internal*/
function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
var options = host.getCompilerOptions();
- if (sourceFile.kind === 280 /* Bundle */) {
+ if (sourceFile.kind === 285 /* Bundle */) {
return getOutputPathsForBundle(options, forceDtsPaths);
}
else {
@@ -81923,19 +82969,13 @@
var isJs = ts.isSourceFileJS(sourceFile);
var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
}
}
ts.getOutputPathsFor = getOutputPathsFor;
function getSourceMapFilePath(jsFilePath, options) {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
- function createDefaultBundleInfo() {
- return {
- originalOffset: -1,
- totalLength: -1
- };
- }
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
@@ -81958,9 +82998,91 @@
return ".js" /* Js */;
}
ts.getOutputExtension = getOutputExtension;
+ function rootDirOfOptions(configFile) {
+ return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.assertDefined(configFile.options.configFilePath));
+ }
+ function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
+ return outputDir ?
+ ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
+ inputFileName;
+ }
+ /* @internal */
+ function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
+ ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(inputFileName));
+ return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
+ }
+ ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
+ function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
+ var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
+ var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
+ ".json" /* Json */ :
+ ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
+ ".jsx" /* Jsx */ :
+ ".js" /* Js */);
+ return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.assertDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
+ outputFileName :
+ undefined;
+ }
+ /*@internal*/
+ function getAllProjectOutputs(configFile, ignoreCase) {
+ var outputs;
+ var addOutput = function (path) { return path && (outputs || (outputs = [])).push(path); };
+ if (configFile.options.outFile || configFile.options.out) {
+ var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ addOutput(jsFilePath);
+ addOutput(sourceMapFilePath);
+ addOutput(declarationFilePath);
+ addOutput(declarationMapPath);
+ addOutput(buildInfoPath);
+ }
+ else {
+ for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
+ var inputFileName = _c[_b];
+ if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
+ continue;
+ var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ addOutput(js);
+ if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
+ continue;
+ if (configFile.options.sourceMap) {
+ addOutput(js + ".map");
+ }
+ if (ts.getEmitDeclarations(configFile.options) && ts.hasTSFileExtension(inputFileName)) {
+ var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
+ addOutput(dts);
+ if (configFile.options.declarationMap) {
+ addOutput(dts + ".map");
+ }
+ }
+ }
+ addOutput(getOutputPathForBuildInfo(configFile.options));
+ }
+ return outputs || ts.emptyArray;
+ }
+ ts.getAllProjectOutputs = getAllProjectOutputs;
+ /*@internal*/
+ function getFirstProjectOutput(configFile, ignoreCase) {
+ if (configFile.options.outFile || configFile.options.out) {
+ var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
+ return ts.Debug.assertDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
+ }
+ for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
+ var inputFileName = _b[_a];
+ if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
+ continue;
+ var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ if (jsFilePath)
+ return jsFilePath;
+ }
+ var buildInfoPath = getOutputPathForBuildInfo(configFile.options);
+ if (buildInfoPath)
+ return buildInfoPath;
+ return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
+ }
+ ts.getFirstProjectOutput = getFirstProjectOutput;
/*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers, onlyBuildInfo) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -81968,12 +83090,12 @@
var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
var writer = ts.createTextWriter(newLine);
var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit;
- var bundleInfo = createDefaultBundleInfo();
+ var bundleBuildInfo;
var emitSkipped = false;
var exportedModulesFromDeclarationEmit;
// Emit each output file
enter();
- forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles);
+ forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile);
exit();
return {
emitSkipped: emitSkipped,
@@ -81983,9 +83105,16 @@
exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
+ bundleBuildInfo = {
+ commonSourceDirectory: host.getCommonSourceDirectory(),
+ sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return file.fileName; })
+ };
+ }
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
+ emitBuildInfo(bundleBuildInfo, buildInfoPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
if (jsFilePath) {
@@ -81994,8 +83123,8 @@
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
- if (bundleInfoPath) {
- emittedFilesList.push(bundleInfoPath);
+ if (buildInfoPath) {
+ emittedFilesList.push(buildInfoPath);
}
}
if (declarationFilePath) {
@@ -82006,8 +83135,21 @@
}
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
- if (emitOnlyDtsFiles || !jsFilePath) {
+ function emitBuildInfo(bundle, buildInfoPath) {
+ // Write build information if applicable
+ if (!buildInfoPath || targetSourceFile || emitSkipped)
+ return;
+ var program = host.getProgramBuildInfo();
+ if (!bundle && !program)
+ return;
+ if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
+ emitSkipped = true;
+ return;
+ }
+ ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: ts.version }), /*writeByteOrderMark*/ false);
+ }
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
+ if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
return;
}
// Make sure not to write js file and source map file if any of them cannot be written
@@ -82027,6 +83169,7 @@
inlineSourceMap: compilerOptions.inlineSourceMap,
inlineSources: compilerOptions.inlineSources,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ writeBundleFileInfo: !!bundleBuildInfo
};
// Create a printer to print the nodes
var printer = createPrinter(printerOptions, {
@@ -82037,12 +83180,14 @@
substituteNode: transform.substituteNode,
});
ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions);
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
// Clean up emit nodes on parse tree
transform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.js = printer.bundleFileInfo;
}
function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) {
- if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
+ if (!sourceFileOrBundle || !(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
return;
}
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
@@ -82071,6 +83216,8 @@
inlineSourceMap: compilerOptions.inlineSourceMap,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
onlyPrintJsDocStyle: true,
+ writeBundleFileInfo: !!bundleBuildInfo,
+ recordInternalSection: !!bundleBuildInfo
};
var declarationPrinter = createPrinter(printerOptions, {
// resolver hooks
@@ -82083,18 +83230,20 @@
emitSkipped = emitSkipped || declBlocked;
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, {
+ printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
sourceMap: compilerOptions.declarationMap,
sourceRoot: compilerOptions.sourceRoot,
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
- if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) {
+ if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 284 /* SourceFile */) {
var sourceFile = declarationTransform.transformed[0];
exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
}
}
declarationTransform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
}
function collectLinkedAliases(node) {
if (ts.isExportAssignment(node)) {
@@ -82109,16 +83258,16 @@
}
ts.forEachChild(node, collectLinkedAliases);
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) {
- var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined;
- var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined;
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
+ var bundle = sourceFileOrBundle.kind === 285 /* Bundle */ ? sourceFileOrBundle : undefined;
+ var sourceFile = sourceFileOrBundle.kind === 284 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
var sourceMapGenerator;
if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
}
if (bundle) {
- printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator);
+ printer.writeBundle(bundle, writer, sourceMapGenerator);
}
else {
printer.writeFile(sourceFile, writer, sourceMapGenerator);
@@ -82147,18 +83296,12 @@
}
// Write the output file
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
- // Write bundled offset information if applicable
- if (bundleInfoPath) {
- bundleInfo.totalLength = writer.getTextPos();
- ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false);
- }
// Reset state
writer.clear();
- bundleInfo = createDefaultBundleInfo();
}
function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
- && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
+ && (sourceFileOrBundle.kind !== 284 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
}
function getSourceRoot(mapOptions) {
// Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
@@ -82215,6 +83358,167 @@
}
}
ts.emitFiles = emitFiles;
+ /*@internal*/
+ function getBuildInfoText(buildInfo) {
+ return JSON.stringify(buildInfo, undefined, 2);
+ }
+ ts.getBuildInfoText = getBuildInfoText;
+ /*@internal*/
+ function getBuildInfo(buildInfoText) {
+ return JSON.parse(buildInfoText);
+ }
+ ts.getBuildInfo = getBuildInfo;
+ /*@internal*/
+ ts.notImplementedResolver = {
+ hasGlobalName: ts.notImplemented,
+ getReferencedExportContainer: ts.notImplemented,
+ getReferencedImportDeclaration: ts.notImplemented,
+ getReferencedDeclarationWithCollidingName: ts.notImplemented,
+ isDeclarationWithCollidingName: ts.notImplemented,
+ isValueAliasDeclaration: ts.notImplemented,
+ isReferencedAliasDeclaration: ts.notImplemented,
+ isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
+ getNodeCheckFlags: ts.notImplemented,
+ isDeclarationVisible: ts.notImplemented,
+ isLateBound: function (_node) { return false; },
+ collectLinkedAliases: ts.notImplemented,
+ isImplementationOfOverload: ts.notImplemented,
+ isRequiredInitializedParameter: ts.notImplemented,
+ isOptionalUninitializedParameterProperty: ts.notImplemented,
+ isExpandoFunctionDeclaration: ts.notImplemented,
+ getPropertiesOfContainerFunction: ts.notImplemented,
+ createTypeOfDeclaration: ts.notImplemented,
+ createReturnTypeOfSignatureDeclaration: ts.notImplemented,
+ createTypeOfExpression: ts.notImplemented,
+ createLiteralConstValue: ts.notImplemented,
+ isSymbolAccessible: ts.notImplemented,
+ isEntityNameVisible: ts.notImplemented,
+ // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
+ getConstantValue: ts.notImplemented,
+ getReferencedValueDeclaration: ts.notImplemented,
+ getTypeReferenceSerializationKind: ts.notImplemented,
+ isOptionalParameter: ts.notImplemented,
+ moduleExportsSomeValue: ts.notImplemented,
+ isArgumentsLocalBinding: ts.notImplemented,
+ getExternalModuleFileFromDeclaration: ts.notImplemented,
+ getTypeReferenceDirectivesForEntityName: ts.notImplemented,
+ getTypeReferenceDirectivesForSymbol: ts.notImplemented,
+ isLiteralConstDeclaration: ts.notImplemented,
+ getJsxFactoryEntity: ts.notImplemented,
+ getAllAccessorDeclarations: ts.notImplemented,
+ getSymbolOfExternalModuleSpecifier: ts.notImplemented,
+ isBindingCapturedByNode: ts.notImplemented,
+ };
+ function createSourceFilesFromBundleBuildInfo(bundle) {
+ var sourceFiles = bundle.sourceFiles.map(function (fileName) {
+ var sourceFile = ts.createNode(284 /* SourceFile */, 0, 0);
+ sourceFile.fileName = fileName;
+ sourceFile.text = "";
+ sourceFile.statements = ts.createNodeArray();
+ return sourceFile;
+ });
+ var jsBundle = ts.Debug.assertDefined(bundle.js);
+ ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
+ var sourceFile = sourceFiles[prologueInfo.file];
+ sourceFile.text = prologueInfo.text;
+ sourceFile.end = prologueInfo.text.length;
+ sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
+ var statement = ts.createNode(221 /* ExpressionStatement */, directive.pos, directive.end);
+ statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
+ statement.expression.text = directive.expression.text;
+ return statement;
+ }));
+ });
+ return sourceFiles;
+ }
+ /*@internal*/
+ function emitUsingBuildInfo(config, host, getCommandLine) {
+ var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
+ var buildInfoText = host.readFile(ts.Debug.assertDefined(buildInfoPath));
+ if (!buildInfoText)
+ return buildInfoPath;
+ var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath));
+ if (!jsFileText)
+ return jsFilePath;
+ var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
+ // error if no source map or for now if inline sourcemap
+ if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
+ return sourceMapFilePath || "inline sourcemap decoding";
+ // read declaration text
+ var declarationText = declarationFilePath && host.readFile(declarationFilePath);
+ if (declarationFilePath && !declarationText)
+ return declarationFilePath;
+ var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
+ // error if no source map or for now if inline sourcemap
+ if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
+ return declarationMapPath || "inline sourcemap decoding";
+ var buildInfo = getBuildInfo(buildInfoText);
+ if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
+ return buildInfoPath;
+ var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo,
+ /*onlyOwnText*/ true);
+ var outputFiles = [];
+ var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
+ var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle);
+ var emitHost = {
+ getPrependNodes: ts.memoize(function () { return prependNodes.concat([ownPrependInput]); }),
+ getCanonicalFileName: host.getCanonicalFileName,
+ getCommonSourceDirectory: function () { return buildInfo.bundle.commonSourceDirectory; },
+ getCompilerOptions: function () { return config.options; },
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ getNewLine: function () { return host.getNewLine(); },
+ getSourceFile: ts.returnUndefined,
+ getSourceFileByPath: ts.returnUndefined,
+ getSourceFiles: function () { return sourceFilesForJsEmit; },
+ getLibFileFromReference: ts.notImplemented,
+ isSourceFileFromExternalLibrary: ts.returnFalse,
+ getResolvedProjectReferenceToRedirect: ts.returnUndefined,
+ writeFile: function (name, text, writeByteOrderMark) {
+ switch (name) {
+ case jsFilePath:
+ if (jsFileText === text)
+ return;
+ break;
+ case sourceMapFilePath:
+ if (sourceMapText === text)
+ return;
+ break;
+ case buildInfoPath:
+ var newBuildInfo = getBuildInfo(text);
+ newBuildInfo.program = buildInfo.program;
+ // Update sourceFileInfo
+ var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
+ newBuildInfo.bundle.js.sources = js.sources;
+ if (dts) {
+ newBuildInfo.bundle.dts.sources = dts.sources;
+ }
+ newBuildInfo.bundle.sourceFiles = sourceFiles;
+ outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
+ return;
+ case declarationFilePath:
+ if (declarationText === text)
+ return;
+ break;
+ case declarationMapPath:
+ if (declarationMapText === text)
+ return;
+ break;
+ default:
+ ts.Debug.fail("Unexpected path: " + name);
+ }
+ outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
+ },
+ isEmitBlocked: ts.returnFalse,
+ readFile: function (f) { return host.readFile(f); },
+ fileExists: function (f) { return host.fileExists(f); },
+ directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }),
+ useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
+ getProgramBuildInfo: ts.returnUndefined
+ };
+ emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, /*emitOnlyDtsFiles*/ false, ts.getTransformers(config.options));
+ return outputFiles;
+ }
+ ts.emitUsingBuildInfo = emitUsingBuildInfo;
var PipelinePhase;
(function (PipelinePhase) {
PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
@@ -82243,6 +83547,10 @@
var ownWriter; // Reusable `EmitTextWriter` for basic printing.
var write = writeBase;
var isOwnFileEmit;
+ var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
+ var recordInternalSection = printerOptions.recordInternalSection;
+ var sourceFileTextPos = 0;
+ var sourceFileTextKind = "text" /* Text */;
// Source Maps
var sourceMapsDisabled = true;
var sourceMapGenerator;
@@ -82268,7 +83576,8 @@
writeNode: writeNode,
writeList: writeList,
writeFile: writeFile,
- writeBundle: writeBundle
+ writeBundle: writeBundle,
+ bundleFileInfo: bundleFileInfo
};
function printNode(hint, node, sourceFile) {
switch (hint) {
@@ -82283,9 +83592,9 @@
break;
}
switch (node.kind) {
- case 279 /* SourceFile */: return printFile(node);
- case 280 /* Bundle */: return printBundle(node);
- case 281 /* UnparsedSource */: return printUnparsedSource(node);
+ case 284 /* SourceFile */: return printFile(node);
+ case 285 /* Bundle */: return printBundle(node);
+ case 286 /* UnparsedSource */: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -82295,7 +83604,7 @@
return endPrint();
}
function printBundle(bundle) {
- writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined);
+ writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
return endPrint();
}
function printFile(sourceFile) {
@@ -82323,7 +83632,49 @@
reset();
writer = previousWriter;
}
- function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) {
+ function getTextPosWithWriteLine() {
+ return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
+ }
+ function updateOrPushBundleFileTextLike(pos, end, kind) {
+ var last = ts.lastOrUndefined(bundleFileInfo.sections);
+ if (last && last.kind === kind) {
+ last.end = end;
+ }
+ else {
+ bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
+ }
+ }
+ function recordBundleFileInternalSectionStart(node) {
+ if (recordInternalSection &&
+ bundleFileInfo &&
+ currentSourceFile &&
+ (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
+ ts.isInternalDeclaration(node, currentSourceFile) &&
+ sourceFileTextKind !== "internal" /* Internal */) {
+ var prevSourceFileTextKind = sourceFileTextKind;
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = "internal" /* Internal */;
+ return prevSourceFileTextKind;
+ }
+ return undefined;
+ }
+ function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
+ if (prevSourceFileTextKind) {
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = prevSourceFileTextKind;
+ }
+ }
+ function recordBundleFileTextLikeSection(end) {
+ if (sourceFileTextPos < end) {
+ updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
+ return true;
+ }
+ return false;
+ }
+ function writeBundle(bundle, output, sourceMapGenerator) {
+ var _a;
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output, sourceMapGenerator);
@@ -82331,18 +83682,49 @@
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
- var prepend = _b[_a];
+ for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
+ var prepend = _c[_b];
writeLine();
+ var pos = writer.getTextPos();
+ var savedSections = bundleFileInfo && bundleFileInfo.sections;
+ if (savedSections)
+ bundleFileInfo.sections = [];
print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
+ if (bundleFileInfo) {
+ var newSections = bundleFileInfo.sections;
+ bundleFileInfo.sections = savedSections;
+ if (prepend.oldFileOfCurrentEmit)
+ (_a = bundleFileInfo.sections).push.apply(_a, newSections);
+ else {
+ newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prepend" /* Prepend */, data: prepend.fileName, texts: newSections });
}
- if (bundleInfo) {
- bundleInfo.originalOffset = writer.getTextPos();
}
- for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
- var sourceFile = _d[_c];
+ }
+ sourceFileTextPos = getTextPosWithWriteLine();
+ for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
+ var sourceFile = _e[_d];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
+ if (bundleFileInfo && bundle.sourceFiles.length) {
+ var end = writer.getTextPos();
+ if (recordBundleFileTextLikeSection(end)) {
+ // Store prologues
+ var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
+ if (prologues) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.prologues = prologues;
+ }
+ // Store helpes
+ var helpers = getHelpersFromBundledSourceFiles(bundle);
+ if (helpers) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.helpers = helpers;
+ }
+ }
+ }
reset();
writer = previousWriter;
}
@@ -82412,8 +83794,10 @@
function emit(node) {
if (node === undefined)
return;
+ var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
pipelinePhase(4 /* Unspecified */, node);
+ recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
}
function emitIdentifierName(node) {
if (node === undefined)
@@ -82440,12 +83824,12 @@
}
// falls through
case 2 /* Comments */:
- if (!commentsDisabled && node.kind !== 279 /* SourceFile */) {
+ if (!commentsDisabled && node.kind !== 284 /* SourceFile */) {
return pipelineEmitWithComments;
}
// falls through
case 3 /* SourceMaps */:
- if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) {
+ if (!sourceMapsDisabled && node.kind !== 284 /* SourceFile */ && !ts.isInJsonFile(node)) {
return pipelineEmitWithSourceMap;
}
// falls through
@@ -82482,8 +83866,16 @@
case 16 /* TemplateMiddle */:
case 17 /* TemplateTail */:
return emitLiteral(node);
- case 281 /* UnparsedSource */:
- return emitUnparsedSource(node);
+ case 286 /* UnparsedSource */:
+ case 280 /* UnparsedPrepend */:
+ return emitUnparsedSourceOrPrepend(node);
+ case 279 /* UnparsedPrologue */:
+ return writeUnparsedNode(node);
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return emitUnparsedTextLike(node);
+ case 283 /* UnparsedSyntheticReference */:
+ return emitUnparsedSyntheticReference(node);
// Identifiers
case 72 /* Identifier */:
return emitIdentifier(node);
@@ -82527,7 +83919,7 @@
return emitTypeReference(node);
case 165 /* FunctionType */:
return emitFunctionType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return emitJSDocFunctionType(node);
case 166 /* ConstructorType */:
return emitConstructorType(node);
@@ -82565,20 +83957,20 @@
return emitLiteralType(node);
case 183 /* ImportType */:
return emitImportTypeNode(node);
- case 284 /* JSDocAllType */:
+ case 289 /* JSDocAllType */:
writePunctuation("*");
return;
- case 285 /* JSDocUnknownType */:
+ case 290 /* JSDocUnknownType */:
writePunctuation("?");
return;
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return emitJSDocNullableType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return emitJSDocNonNullableType(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return emitJSDocOptionalType(node);
case 172 /* RestType */:
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return emitRestOrJSDocVariadicType(node);
// Binding patterns
case 184 /* ObjectBindingPattern */:
@@ -82716,30 +84108,30 @@
case 278 /* EnumMember */:
return emitEnumMember(node);
// JSDoc nodes (only used in codefixes currently)
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return emitJSDocPropertyLikeTag(node);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return emitJSDocSimpleTypedTag(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return emitJSDocAugmentsTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return emitJSDocTemplateTag(node);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return emitJSDocTypedefTag(node);
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return emitJSDocCallbackTag(node);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return emitJSDocSignature(node);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return emitJSDocTypeLiteral(node);
- case 296 /* JSDocClassTag */:
- case 294 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
return emitJSDocSimpleTag(node);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return emitJSDoc(node);
// Transformation nodes (ignored)
}
@@ -82838,9 +84230,9 @@
case 264 /* JsxFragment */:
return emitJsxFragment(node);
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return emitPartiallyEmittedExpression(node);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return emitCommaList(node);
}
}
@@ -82856,22 +84248,45 @@
var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node);
pipelinePhase(hint, substituteNode(hint, node));
}
+ function getHelpersFromBundledSourceFiles(bundle) {
+ var result;
+ if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
+ return undefined;
+ }
+ var bundledHelpers = ts.createMap();
+ for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
+ var helpers = getSortedEmitHelpers(sourceFile);
+ if (!helpers)
+ continue;
+ for (var _c = 0, helpers_3 = helpers; _c < helpers_3.length; _c++) {
+ var helper = helpers_3[_c];
+ if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
+ bundledHelpers.set(helper.name, true);
+ (result || (result = [])).push(helper.name);
+ }
+ }
+ }
+ return result;
+ }
function emitHelpers(node) {
var helpersEmitted = false;
- var bundle = node.kind === 280 /* Bundle */ ? node : undefined;
+ var bundle = node.kind === 285 /* Bundle */ ? node : undefined;
if (bundle && moduleKind === ts.ModuleKind.None) {
return;
}
- var numNodes = bundle ? bundle.sourceFiles.length : 1;
+ var numPrepends = bundle ? bundle.prepends.length : 0;
+ var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
for (var i = 0; i < numNodes; i++) {
- var currentNode = bundle ? bundle.sourceFiles[i] : node;
- var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile;
- var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined;
- var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit;
- var helpers = ts.getEmitHelpers(currentNode);
+ var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
+ var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
+ var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
+ var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
+ var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
if (helpers) {
- for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
- var helper = _b[_a];
+ for (var _a = 0, helpers_4 = helpers; _a < helpers_4.length; _a++) {
+ var helper = helpers_4[_a];
if (!helper.scoped) {
// Skip the helper if it can be skipped and the noEmitHelpers compiler
// option is set, or if it can be imported and the importHelpers compiler
@@ -82891,18 +84306,25 @@
// Skip the helper if it is scoped and we are emitting bundled helpers
continue;
}
+ var pos = getTextPosWithWriteLine();
if (typeof helper.text === "string") {
writeLines(helper.text);
}
else {
writeLines(helper.text(makeFileLevelOptimisticUniqueName));
}
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
helpersEmitted = true;
}
}
}
return helpersEmitted;
}
+ function getSortedEmitHelpers(node) {
+ var helpers = ts.getEmitHelpers(node);
+ return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
+ }
//
// Literals/Pseudo-literals
//
@@ -82929,8 +84351,42 @@
}
}
// SyntaxKind.UnparsedSource
- function emitUnparsedSource(unparsed) {
- writer.rawWrite(unparsed.text);
+ // SyntaxKind.UnparsedPrepend
+ function emitUnparsedSourceOrPrepend(unparsed) {
+ for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
+ var text = _b[_a];
+ writeLine();
+ emit(text);
+ }
+ }
+ // SyntaxKind.UnparsedPrologue
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ // SyntaxKind.UnparsedSyntheticReference
+ function writeUnparsedNode(unparsed) {
+ writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
+ }
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ function emitUnparsedTextLike(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 281 /* UnparsedText */ ?
+ "text" /* Text */ :
+ "internal" /* Internal */);
+ }
+ }
+ // SyntaxKind.UnparsedSyntheticReference
+ function emitUnparsedSyntheticReference(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ var section = ts.clone(unparsed.section);
+ section.pos = pos;
+ section.end = writer.getTextPos();
+ bundleFileInfo.sections.push(section);
+ }
}
//
// Identifiers
@@ -82985,7 +84441,7 @@
emit(node.dotDotDotToken);
emitNodeWithWriter(node.name, writeParameter);
emit(node.questionToken);
- if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) {
+ if (node.parent && node.parent.kind === 294 /* JSDocFunctionType */ && !node.name) {
emit(node.type);
}
else {
@@ -83865,7 +85321,7 @@
}
function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
// Emit all the prologue directives (like "use strict").
- var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true);
+ var statementOffset = emitPrologueDirectives(body.statements);
var pos = writer.getTextPos();
emitHelpers(body);
if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
@@ -84125,7 +85581,7 @@
writePunctuation(">");
}
function emitJsxText(node) {
- writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true));
+ writer.writeLiteral(node.text);
}
function emitJsxClosingElementOrFragment(node) {
writePunctuation("</");
@@ -84270,7 +85726,7 @@
}
}
if (node.tags) {
- if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) {
+ if (node.tags.length === 1 && node.tags[0].kind === 307 /* JSDocTypeTag */ && !node.comment) {
writeSpace();
emit(node.tags[0]);
}
@@ -84304,7 +85760,7 @@
function emitJSDocTypedefTag(tag) {
emitJSDocTagName(tag.tagName);
if (tag.typeExpression) {
- if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
emitJSDocTypeExpression(tag.typeExpression);
}
else {
@@ -84323,7 +85779,7 @@
emit(tag.fullName);
}
emitJSDocComment(tag.comment);
- if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) {
+ if (tag.typeExpression && tag.typeExpression.kind === 297 /* JSDocTypeLiteral */) {
emitJSDocTypeLiteral(tag.typeExpression);
}
}
@@ -84410,6 +85866,16 @@
}
function emitSyntheticTripleSlashReferencesIfNeeded(node) {
emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
+ for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
+ for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
+ var ref = _d[_c];
+ emit(ref);
+ writeLine();
+ }
+ }
+ }
}
function emitTripleSlashDirectivesIfNeeded(node) {
if (node.isDeclarationFile)
@@ -84417,7 +85883,10 @@
}
function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
if (hasNoDefaultLib) {
+ var pos = writer.getTextPos();
writeComment("/// <reference no-default-lib=\"true\"/>");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
writeLine();
}
if (currentSourceFile && currentSourceFile.moduleName) {
@@ -84438,17 +85907,26 @@
}
for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
var directive = files_1[_c];
+ var pos = writer.getTextPos();
writeComment("/// <reference path=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
writeLine();
}
- for (var _d = 0, types_18 = types; _d < types_18.length; _d++) {
- var directive = types_18[_d];
+ for (var _d = 0, types_19 = types; _d < types_19.length; _d++) {
+ var directive = types_19[_d];
+ var pos = writer.getTextPos();
writeComment("/// <reference types=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
writeLine();
}
for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
var directive = libs_1[_e];
+ var pos = writer.getTextPos();
writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
writeLine();
}
}
@@ -84473,16 +85951,22 @@
* Emits any prologue directives at the start of a Statement list, returning the
* number of prologue directives written to the output.
*/
- function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) {
+ function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
+ var needsToSetSourceFile = !!sourceFile;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (ts.isPrologueDirective(statement)) {
var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
if (shouldEmitPrologueDirective) {
- if (startWithNewLine || i > 0) {
- writeLine();
+ if (needsToSetSourceFile) {
+ needsToSetSourceFile = false;
+ setSourceFile(sourceFile);
}
+ writeLine();
+ var pos = writer.getTextPos();
emit(statement);
+ if (recordBundleFileSection && bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
if (seenPrologueDirectives) {
seenPrologueDirectives.set(statement.expression.text, true);
}
@@ -84495,23 +85979,70 @@
}
return statements.length;
}
+ function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
+ for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
+ var prologue = prologues_1[_a];
+ if (!seenPrologueDirectives.has(prologue.data)) {
+ writeLine();
+ var pos = writer.getTextPos();
+ emit(prologue);
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
+ if (seenPrologueDirectives) {
+ seenPrologueDirectives.set(prologue.data, true);
+ }
+ }
+ }
+ }
function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
if (ts.isSourceFile(sourceFileOrBundle)) {
- setSourceFile(sourceFileOrBundle);
- emitPrologueDirectives(sourceFileOrBundle.statements);
+ emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
}
else {
var seenPrologueDirectives = ts.createMap();
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
- setSourceFile(sourceFile);
- emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
+ emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
}
setSourceFile(undefined);
}
}
+ function getPrologueDirectivesFromBundledSourceFiles(bundle) {
+ var seenPrologueDirectives = ts.createMap();
+ var prologues;
+ for (var index = 0; index < bundle.sourceFiles.length; index++) {
+ var sourceFile = bundle.sourceFiles[index];
+ var directives = void 0;
+ var end = 0;
+ for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
+ var statement = _b[_a];
+ if (!ts.isPrologueDirective(statement))
+ break;
+ if (seenPrologueDirectives.has(statement.expression.text))
+ continue;
+ seenPrologueDirectives.set(statement.expression.text, true);
+ (directives || (directives = [])).push({
+ pos: statement.pos,
+ end: statement.end,
+ expression: {
+ pos: statement.expression.pos,
+ end: statement.expression.end,
+ text: statement.expression.text
+ }
+ });
+ end = end < statement.end ? statement.end : end;
+ }
+ if (directives)
+ (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
+ }
+ return prologues;
+ }
function emitShebangIfNeeded(sourceFileOrBundle) {
- if (ts.isSourceFile(sourceFileOrBundle)) {
+ if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
var shebang = ts.getShebang(sourceFileOrBundle.text);
if (shebang) {
writeComment(shebang);
@@ -84520,11 +86051,18 @@
}
}
else {
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ ts.Debug.assertNode(prepend, ts.isUnparsedSource);
+ if (emitShebangIfNeeded(prepend)) {
+ return true;
+ }
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
// Emit only the first encountered shebang
if (emitShebangIfNeeded(sourceFile)) {
- break;
+ return true;
}
}
}
@@ -84727,6 +86265,7 @@
}
// Emit each child.
var previousSibling = void 0;
+ var previousSourceFileTextKind = void 0;
var shouldDecreaseIndentAfterEmit = false;
for (var i = 0; i < count; i++) {
var child = children[start + i];
@@ -84747,6 +86286,7 @@
emitLeadingCommentsOfPosition(previousSibling.end);
}
writeDelimiter(format);
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write either a line terminator or whitespace to separate the elements.
if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
// If a synthesized node in a single-line list starts on a new
@@ -84763,6 +86303,7 @@
}
}
// Emit this child.
+ previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
if (shouldEmitInterveningComments) {
if (emitTrailingCommentsOfPosition) {
var commentRange = ts.getCommentRange(child);
@@ -84797,6 +86338,7 @@
if (format & 128 /* Indented */) {
decreaseIndent();
}
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write the closing line terminator or closing whitespace.
if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
writeLine();
@@ -84898,7 +86440,6 @@
if (line.length) {
writeLine();
write(line);
- writer.rawWrite(newLine);
}
}
}
@@ -85412,7 +86953,7 @@
hasWrittenComment = false;
var emitFlags = ts.getEmitFlags(node);
var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
- var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 312 /* 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 === 11 /* JsxText */;
@@ -85672,19 +87213,28 @@
return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
}
// Source Maps
+ function getParsedSourceMap(node) {
+ if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
+ node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
+ }
+ return node.parsedSourceMap || undefined;
+ }
function pipelineEmitWithSourceMap(hint, node) {
var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node);
- if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) {
- var parsed = ts.tryParseRawSourceMap(node.sourceMapText);
- if (parsed) {
- sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath);
+ if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
+ pipelinePhase(hint, node);
+ }
+ else if (ts.isUnparsedNode(node)) {
+ var parsed = getParsedSourceMap(node.parent);
+ if (parsed && sourceMapGenerator) {
+ sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
}
pipelinePhase(hint, node);
}
else {
var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
var emitFlags = ts.getEmitFlags(node);
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitSourcePos(source, skipSourceTrivia(source, pos));
@@ -85697,7 +87247,7 @@
else {
pipelinePhase(hint, node);
}
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitSourcePos(source, end);
@@ -85825,7 +87375,8 @@
writeFile: host.writeFile && writeFile,
addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
addOrDeleteFile: addOrDeleteFile,
- clearCache: clearCache
+ clearCache: clearCache,
+ realpath: host.realpath && realpath
};
function toPath(fileName) {
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
@@ -85922,7 +87473,7 @@
var rootDirPath = toPath(rootDir);
var result = tryReadDirectory(rootDir, rootDirPath);
if (result) {
- return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries);
+ return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
}
return host.readDirectory(rootDir, extensions, excludes, includes, depth);
function getFileSystemEntries(dir) {
@@ -85933,6 +87484,9 @@
return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
}
}
+ function realpath(s) {
+ return host.realpath ? host.realpath(s) : s;
+ }
function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
if (existingResult) {
@@ -86203,11 +87757,7 @@
function createCompilerHostWorker(options, setParentNodes, system) {
if (system === void 0) { system = ts.sys; }
var existingDirectories = ts.createMap();
- function getCanonicalFileName(fileName) {
- // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
- // otherwise use toLowerCase as a canonical form.
- return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
- }
+ var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
function getSourceFile(fileName, languageVersion, onError) {
var text;
try {
@@ -86332,20 +87882,21 @@
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
- return value || undefined;
+ return value !== false ? value : undefined;
return setReadFileCache(key, fileName);
};
var setReadFileCache = function (key, fileName) {
var newValue = originalReadFile.call(host, fileName);
- readFileCache.set(key, newValue || false);
+ readFileCache.set(key, newValue !== undefined ? newValue : false);
return newValue;
};
host.readFile = function (fileName) {
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
- return value; // could be .d.ts from output
- if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ return value !== false ? value : undefined; // could be .d.ts from output
+ // Cache json or buildInfo
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
return originalReadFile.call(host, fileName);
}
return setReadFileCache(key, fileName);
@@ -86376,7 +87927,7 @@
var key = toPath(fileName);
fileExistsCache.delete(key);
var value = readFileCache.get(key);
- if (value && value !== data) {
+ if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.delete(key);
}
@@ -86822,11 +88373,18 @@
if (rootNames.length) {
for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
var parsedRef = resolvedProjectReferences_1[_i];
- if (parsedRef) {
+ if (!parsedRef)
+ continue;
var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
if (out) {
- var dtsOutfile = ts.changeExtension(out, ".d.ts");
- processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ }
+ else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
+ for (var _a = 0, _b = parsedRef.commandLine.fileNames; _a < _b.length; _a++) {
+ var fileName = _b[_a];
+ if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(fileName)) {
+ processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ }
}
}
}
@@ -86874,8 +88432,8 @@
// not part of the new program.
if (oldProgram && host.onReleaseOldSourceFile) {
var oldSourceFiles = oldProgram.getSourceFiles();
- for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) {
- var oldSourceFile = oldSourceFiles_1[_a];
+ for (var _c = 0, oldSourceFiles_1 = oldSourceFiles; _c < oldSourceFiles_1.length; _c++) {
+ var oldSourceFile = oldSourceFiles_1[_c];
var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
if (shouldCreateNewSourceFile || !newFile ||
// old file wasnt redirect but new file is
@@ -86931,7 +88489,8 @@
getProjectReferenceRedirect: getProjectReferenceRedirect,
getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
- forEachResolvedProjectReference: forEachResolvedProjectReference
+ forEachResolvedProjectReference: forEachResolvedProjectReference,
+ emitBuildInfo: emitBuildInfo
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -86960,7 +88519,7 @@
}
function getCommonSourceDirectory() {
if (commonSourceDirectory === undefined) {
- var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); });
+ var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
// If a rootDir is specified use it as the commonSourceDirectory
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
@@ -87349,7 +88908,8 @@
}
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, getLibFileFromReference: program.getLibFileFromReference, 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) {
+ 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, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
+ getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, 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))
@@ -87358,7 +88918,20 @@
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(); } });
+ } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); } });
+ }
+ function emitBuildInfo(writeFileCallback) {
+ ts.Debug.assert(!options.out && !options.outFile);
+ ts.performance.mark("beforeEmit");
+ var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback),
+ /*targetSourceFile*/ undefined,
+ /*emitOnlyDtsFiles*/ false,
+ /*transformers*/ undefined,
+ /*declaraitonTransformers*/ undefined,
+ /*onlyBuildInfo*/ true);
+ ts.performance.mark("afterEmit");
+ ts.performance.measure("Emit", "beforeEmit", "afterEmit");
+ return emitResult;
}
function getResolvedProjectReferences() {
return resolvedProjectReferences;
@@ -87367,28 +88940,11 @@
return projectReferences;
}
function getPrependNodes() {
- if (!projectReferences) {
- return ts.emptyArray;
- }
- var nodes = [];
- for (var i = 0; i < projectReferences.length; i++) {
- var ref = projectReferences[i];
- var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
- if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
- var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
- // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
- if (!out)
- continue;
- var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- var node = ts.createInputFiles(function (fileName) {
+ return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
var path = toPath(fileName);
var sourceFile = getSourceFileByPath(path);
return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
- }, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath);
- nodes.push(node);
- }
- }
- return nodes;
+ });
}
function isSourceFileFromExternalLibrary(file) {
return !!sourceFilesFoundSearchingNodeModules.get(file.path);
@@ -87460,8 +89016,7 @@
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
ts.performance.mark("beforeEmit");
var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217
- emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -88073,7 +89628,6 @@
if (refFile) {
var redirect = getProjectReferenceRedirect(fileName);
if (redirect) {
- (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName);
fileName = redirect;
// Once we start redirecting to a file, we can potentially come back to it
// via a back-reference from another file in the .d.ts folder. If that happens we'll
@@ -88170,7 +89724,7 @@
var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
return out ?
ts.changeExtension(out, ".d.ts" /* Dts */) :
- ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine);
+ ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
}
/**
* Get the referenced project if the file is input file from that reference project
@@ -88463,18 +90017,29 @@
if (options.declaration === false) {
createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
}
+ if (options.incremental === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
+ }
+ }
+ if (options.tsBuildInfoFile) {
+ if (!ts.isIncrementalCompilation(options)) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
+ }
}
verifyProjectReferences();
// List of collected files is complete; validate exhautiveness if this is a project with a file list
if (options.composite) {
- var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; });
- if (rootNames.length < sourceFiles.length) {
- var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); });
- for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) {
- var file = _a[_i];
- if (normalizedRootNames.indexOf(file) === -1) {
- 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));
- }
+ var rootPaths = rootNames.map(toPath);
+ for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
+ var file = files_3[_i];
+ // Ignore declaration files
+ if (file.isDeclarationFile)
+ continue;
+ // Ignore json file thats from project reference
+ if (ts.isJsonSourceFile(file) && getResolvedProjectReferenceToRedirect(file.fileName))
+ continue;
+ if (rootPaths.indexOf(file.path) === -1) {
+ 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.fileName));
}
}
}
@@ -88657,6 +90222,7 @@
}
}
function verifyProjectReferences() {
+ var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getOutputPathForBuildInfo(options) : undefined;
forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
var parentFile = parent && parent.sourceFile;
@@ -88683,6 +90249,10 @@
createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
}
}
+ if (!parent && buildInfoPath && buildInfoPath === ts.getOutputPathForBuildInfo(options)) {
+ createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
+ hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
+ }
});
}
function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
@@ -88827,11 +90397,32 @@
readFile: function (f) { return directoryStructureHost.readFile(f); },
useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
getCurrentDirectory: function () { return host.getCurrentDirectory(); },
- onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || (function () { return undefined; }),
+ onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
trace: host.trace ? function (s) { return host.trace(s); } : undefined
};
}
ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
+ /* @internal */
+ function createPrependNodes(projectReferences, getCommandLine, readFile) {
+ if (!projectReferences)
+ return ts.emptyArray;
+ var nodes;
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = getCommandLine(ref, i);
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!out)
+ continue;
+ var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
+ (nodes || (nodes = [])).push(node);
+ }
+ }
+ return nodes || ts.emptyArray;
+ }
+ ts.createPrependNodes = createPrependNodes;
function resolveProjectReferencePath(hostOrRef, ref) {
var passedInRef = ref ? ref : hostOrRef;
return ts.resolveConfigFileProjectName(passedInRef.path);
@@ -89028,7 +90619,7 @@
// Create the reference map, and set the file infos
for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
- var version_1 = sourceFile.version;
+ var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined;
if (referencedMap) {
var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
@@ -89083,9 +90674,9 @@
*/
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
+ // They will be committed once it is safe to use them
// eg when calling this api from tsserver, if there is no cancellation of the operation
- // In the other cases the affected files signatures are commited only after the iteration through the result is complete
+ // In the other cases the affected files signatures are committed only after the iteration through the result is complete
var signatureCache = cacheToUpdateSignature || ts.createMap();
var sourceFile = programOfThisState.getSourceFileByPath(path);
if (!sourceFile) {
@@ -89375,11 +90966,14 @@
var affectedSignatures = oldState.currentAffectedFilesSignatures;
ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
}
+ var changedFilesSet = oldState.changedFilesSet;
if (canCopySemanticDiagnostics) {
- ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
+ ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
}
// Copy old state's changed files set
- ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet);
+ if (changedFilesSet) {
+ ts.copyEntries(changedFilesSet, state.changedFilesSet);
+ }
if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit;
state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
@@ -89417,7 +91011,7 @@
// Unchanged file copy diagnostics
var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
if (diagnostics) {
- state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics);
+ state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics);
if (!state.semanticDiagnosticsFromOldState) {
state.semanticDiagnosticsFromOldState = ts.createMap();
}
@@ -89425,8 +91019,45 @@
}
}
});
+ if (oldCompilerOptions &&
+ (oldCompilerOptions.outDir !== compilerOptions.outDir ||
+ oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
+ (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
+ // Add all files to affectedFilesPendingEmit since emit changed
+ state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(function (f) { return f.path; }));
+ if (state.affectedFilesPendingEmitIndex === undefined) {
+ state.affectedFilesPendingEmitIndex = 0;
+ }
+ ts.Debug.assert(state.seenAffectedFiles === undefined);
+ state.seenAffectedFiles = ts.createMap();
+ }
return state;
}
+ function convertToDiagnostics(diagnostics, newProgram) {
+ if (!diagnostics.length)
+ return ts.emptyArray;
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToDiagnosticRelatedInformation(diagnostic, newProgram) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && newProgram.getSourceFileByPath(file), messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToDiagnosticMessageChain(messageText, newProgram) });
+ }
+ function convertToDiagnosticMessageChain(diagnostic, newProgram) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram) });
+ }
/**
* Releases program and other related not needed properties
*/
@@ -89646,8 +91277,11 @@
* 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
*/
- function doneWithAffectedFile(state, affected, isPendingEmit) {
- if (affected === state.program) {
+ function doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit) {
+ if (isBuildInfoEmit) {
+ state.emittedBuildInfo = true;
+ }
+ else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
@@ -89664,8 +91298,8 @@
/**
* Returns the result with affected file
*/
- function toAffectedFileResult(state, result, affected, isPendingEmit) {
- doneWithAffectedFile(state, affected, isPendingEmit);
+ function toAffectedFileResult(state, result, affected, isPendingEmit, isBuildInfoEmit) {
+ doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
return { result: result, affected: affected };
}
/**
@@ -89688,6 +91322,77 @@
}
return diagnostics;
}
+ /**
+ * Gets the program information to be emitted in buildInfo so that we can use it to create new program
+ */
+ function getProgramBuildInfo(state) {
+ if (state.compilerOptions.outFile || state.compilerOptions.out)
+ return undefined;
+ var fileInfos = {};
+ state.fileInfos.forEach(function (value, key) {
+ var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
+ fileInfos[key] = signature === undefined ? value : { version: value.version, signature: signature };
+ });
+ var result = { fileInfos: fileInfos, options: state.compilerOptions };
+ if (state.referencedMap) {
+ var referencedMap_1 = {};
+ state.referencedMap.forEach(function (value, key) {
+ referencedMap_1[key] = ts.arrayFrom(value.keys());
+ });
+ result.referencedMap = referencedMap_1;
+ }
+ if (state.exportedModulesMap) {
+ var exportedModulesMap_1 = {};
+ state.exportedModulesMap.forEach(function (value, key) {
+ var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
+ // Not in temporary cache, use existing value
+ if (newValue === undefined)
+ exportedModulesMap_1[key] = ts.arrayFrom(value.keys());
+ // Value in cache and has updated value map, use that
+ else if (newValue)
+ exportedModulesMap_1[key] = ts.arrayFrom(newValue.keys());
+ });
+ result.exportedModulesMap = exportedModulesMap_1;
+ }
+ if (state.semanticDiagnosticsPerFile) {
+ var semanticDiagnosticsPerFile_1 = [];
+ // Currently not recording actual errors since those mean no emit for tsc --build
+ state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ?
+ [
+ key,
+ state.hasReusableDiagnostic ?
+ value :
+ convertToReusableDiagnostics(value)
+ ] :
+ key); });
+ result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1;
+ }
+ return result;
+ }
+ function convertToReusableDiagnostics(diagnostics) {
+ ts.Debug.assert(!!diagnostics.length);
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToReusableDiagnosticRelatedInformation(diagnostic);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToReusableDiagnosticRelatedInformation(diagnostic) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && file.path, messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToReusableDiagnosticMessageChain(messageText) });
+ }
+ function convertToReusableDiagnosticMessageChain(diagnostic) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next) });
+ }
var BuilderProgramKind;
(function (BuilderProgramKind) {
BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
@@ -89744,6 +91449,7 @@
var computeHash = host.createHash || ts.generateDjb2Hash;
var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
var backupState;
+ newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state); };
// To ensure that we arent storing any references to old program or new program without state
newProgram = undefined; // TODO: GH#18217
oldProgram = undefined;
@@ -89787,8 +91493,17 @@
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
affected = getNextAffectedFilePendingEmit(state);
if (!affected) {
+ if (state.emittedBuildInfo) {
return undefined;
}
+ var affected_1 = ts.Debug.assertDefined(state.program);
+ return toAffectedFileResult(state,
+ // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
+ // Otherwise just affected file
+ affected_1.emitBuildInfo(writeFile || host.writeFile, cancellationToken), affected_1,
+ /*isPendingEmitFile*/ false,
+ /*isBuildInfoEmit*/ true);
+ }
isPendingEmitFile = true;
}
else {
@@ -89913,13 +91628,60 @@
}
var diagnostics;
for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
- var sourceFile_2 = _a[_i];
- diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken));
+ var sourceFile_1 = _a[_i];
+ diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
}
return diagnostics || ts.emptyArray;
}
}
ts.createBuilderProgram = createBuilderProgram;
+ function getMapOfReferencedSet(mapLike) {
+ if (!mapLike)
+ return undefined;
+ var map = ts.createMap();
+ // Copies keys/values from template. Note that for..in will not throw if
+ // template is undefined, and instead will just exit the loop.
+ for (var key in mapLike) {
+ if (ts.hasProperty(mapLike, key)) {
+ map.set(key, ts.arrayToSet(mapLike[key]));
+ }
+ }
+ return map;
+ }
+ function createBuildProgramUsingProgramBuildInfo(program) {
+ var fileInfos = ts.createMapFromTemplate(program.fileInfos);
+ var state = {
+ fileInfos: fileInfos,
+ compilerOptions: program.options,
+ referencedMap: getMapOfReferencedSet(program.referencedMap),
+ exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
+ semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return ts.isString(value) ? value : value[0]; }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
+ hasReusableDiagnostic: true
+ };
+ return {
+ getState: function () { return state; },
+ backupState: ts.noop,
+ restoreState: ts.noop,
+ getProgram: ts.notImplemented,
+ getProgramOrUndefined: ts.returnUndefined,
+ releaseProgram: ts.noop,
+ getCompilerOptions: function () { return state.compilerOptions; },
+ getSourceFile: ts.notImplemented,
+ getSourceFiles: ts.notImplemented,
+ getOptionsDiagnostics: ts.notImplemented,
+ getGlobalDiagnostics: ts.notImplemented,
+ getConfigFileParsingDiagnostics: ts.notImplemented,
+ getSyntacticDiagnostics: ts.notImplemented,
+ getDeclarationDiagnostics: ts.notImplemented,
+ getSemanticDiagnostics: ts.notImplemented,
+ emit: ts.notImplemented,
+ getAllDependencies: ts.notImplemented,
+ getCurrentDirectory: ts.notImplemented,
+ emitNextAffectedFile: ts.notImplemented,
+ getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
+ };
+ }
+ ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
return {
getState: ts.notImplemented,
@@ -89939,7 +91701,7 @@
getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
getAllDependencies: ts.notImplemented,
- getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); }
+ getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
};
function getProgram() {
return ts.Debug.assertDefined(state.program);
@@ -89965,10 +91727,10 @@
/*@internal*/
var ts;
(function (ts) {
- function isPathInNodeModulesStartingWithDot(path) {
- return ts.stringContains(path, "/node_modules/.");
+ function isPathIgnored(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); });
}
- ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot;
+ ts.isPathIgnored = isPathIgnored;
ts.maxNumberOfFilesToIterateForInvalidation = 256;
function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
var filesWithChangedSetOfUnresolvedImports;
@@ -90490,7 +92252,7 @@
}
else {
// If something to do with folder/file starting with "." in node_modules folder, skip it
- if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (isPathIgnored(fileOrDirectoryPath))
return false;
// Some file or directory in the watching directory is created
// Return early if it does not have any of the watching extension or not the custom failed lookup path
@@ -90967,6 +92729,8 @@
case ".jsx" /* Jsx */:
case ".json" /* Json */:
return ext;
+ case ".tsbuildinfo" /* TsBuildInfo */:
+ return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
default:
return ts.Debug.assertNever(ext);
}
@@ -91087,22 +92851,18 @@
var diagnostics = program.getConfigFileParsingDiagnostics().slice();
var configFileParsingDiagnosticsLength = diagnostics.length;
ts.addRange(diagnostics, program.getSyntacticDiagnostics());
- var reportSemanticDiagnostics = false;
// If we didn't have any syntactic errors, then also try getting the global and
// semantic errors.
if (diagnostics.length === configFileParsingDiagnosticsLength) {
ts.addRange(diagnostics, program.getOptionsDiagnostics());
ts.addRange(diagnostics, program.getGlobalDiagnostics());
if (diagnostics.length === configFileParsingDiagnosticsLength) {
- reportSemanticDiagnostics = true;
+ ts.addRange(diagnostics, program.getSemanticDiagnostics());
}
}
// Emit and report any errors we ran into.
var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics;
ts.addRange(diagnostics, emitDiagnostics);
- if (reportSemanticDiagnostics) {
- ts.addRange(diagnostics, program.getSemanticDiagnostics());
- }
ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic);
if (writeFileName) {
var currentDir_1 = program.getCurrentDirectory();
@@ -91223,6 +92983,22 @@
}
}
ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
+ function setGetSourceFileAsHashVersioned(compilerHost, host) {
+ var originalGetSourceFile = compilerHost.getSourceFile;
+ var computeHash = host.createHash || ts.generateDjb2Hash;
+ compilerHost.getSourceFile = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
+ if (result) {
+ result.version = computeHash.call(host, result.text);
+ }
+ return result;
+ };
+ }
+ ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
/**
* Creates the watch compiler host that can be extended with config file or root file names and options host
*/
@@ -91248,7 +93024,7 @@
writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
createHash: ts.maybeBind(system, system.createHash),
- createProgram: createProgram
+ createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
};
}
ts.createProgramHost = createProgramHost;
@@ -91258,7 +93034,7 @@
function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
var writeFileName = function (s) { return system.write(s + system.newLine); };
- var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram);
+ var result = createProgramHost(system, createProgram);
ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = function (builderProgram) {
var compilerOptions = builderProgram.getCompilerOptions();
@@ -91297,6 +93073,49 @@
return host;
}
ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
+ function readBuilderProgram(compilerOptions, readFile) {
+ if (compilerOptions.out || compilerOptions.outFile)
+ return undefined;
+ var buildInfoPath = ts.getOutputPathForBuildInfo(compilerOptions);
+ if (!buildInfoPath)
+ return undefined;
+ var content = readFile(buildInfoPath);
+ if (!content)
+ return undefined;
+ var buildInfo = ts.getBuildInfo(content);
+ if (buildInfo.version !== ts.version)
+ return undefined;
+ if (!buildInfo.program)
+ return undefined;
+ return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program);
+ }
+ ts.readBuilderProgram = readBuilderProgram;
+ function createIncrementalCompilerHost(options, system) {
+ if (system === void 0) { system = ts.sys; }
+ var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
+ host.createHash = ts.maybeBind(system, system.createHash);
+ setGetSourceFileAsHashVersioned(host, system);
+ ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
+ return host;
+ }
+ ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
+ function createIncrementalProgram(_a) {
+ var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
+ host = host || createIncrementalCompilerHost(options);
+ createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
+ var oldProgram = readBuilderProgram(options, function (path) { return host.readFile(path); });
+ return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
+ }
+ function performIncrementalCompilation(input) {
+ var system = input.system || ts.sys;
+ var host = input.host || (input.host = createIncrementalCompilerHost(input.options, system));
+ var builderProgram = createIncrementalProgram(input);
+ var exitStatus = emitFilesAndReportErrors(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined);
+ if (input.afterProgramEmitAndDiagnostics)
+ input.afterProgramEmitAndDiagnostics(builderProgram);
+ return exitStatus;
+ }
+ ts.performIncrementalCompilation = performIncrementalCompilation;
})(ts || (ts = {}));
(function (ts) {
function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) {
@@ -91308,7 +93127,6 @@
}
}
ts.createWatchCompilerHost = createWatchCompilerHost;
- var initialVersion = 1;
function createWatchProgram(host) {
var builderProgram;
var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
@@ -91349,10 +93167,12 @@
var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
+ var configFileWatcher;
if (configFileName) {
- watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */);
+ configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */);
}
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
+ ts.setGetSourceFileAsHashVersioned(compilerHost, host);
// Members for CompilerHost
var getNewSourceFile = compilerHost.getSourceFile;
compilerHost.getSourceFile = function (fileName) {
@@ -91393,21 +93213,43 @@
(function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) :
(function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
+ builderProgram = ts.readBuilderProgram(compilerOptions, function (path) { return compilerHost.readFile(path); });
synchronizeProgram();
// Update the wild card directory watch
watchConfigFileWildCardDirectories();
return configFileName ?
- { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } :
- { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames };
+ { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } :
+ { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close };
+ function close() {
+ resolutionCache.clear();
+ ts.clearMap(sourceFilesCache, function (value) {
+ if (value && value.fileWatcher) {
+ value.fileWatcher.close();
+ value.fileWatcher = undefined;
+ }
+ });
+ if (configFileWatcher) {
+ configFileWatcher.close();
+ configFileWatcher = undefined;
+ }
+ if (watchedWildcardDirectories) {
+ ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
+ watchedWildcardDirectories = undefined;
+ }
+ if (missingFilesMap) {
+ ts.clearMap(missingFilesMap, ts.closeFileWatcher);
+ missingFilesMap = undefined;
+ }
+ }
function getCurrentBuilderProgram() {
return builderProgram;
}
function getCurrentProgram() {
- return builderProgram && builderProgram.getProgram();
+ return builderProgram && builderProgram.getProgramOrUndefined();
}
function synchronizeProgram() {
writeLog("Synchronizing program");
- var program = getCurrentProgram();
+ var program = getCurrentBuilderProgram();
if (hasChangedCompilerOptions) {
newLine = updateNewLine();
if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
@@ -91423,19 +93265,19 @@
}
}
else {
- createNewProgram(program, hasInvalidatedResolution);
+ createNewProgram(hasInvalidatedResolution);
}
if (host.afterProgramCreate) {
host.afterProgramCreate(builderProgram);
}
return builderProgram;
}
- function createNewProgram(program, hasInvalidatedResolution) {
+ function createNewProgram(hasInvalidatedResolution) {
// Compile the program
writeLog("CreatingProgramWith::");
writeLog(" roots: " + JSON.stringify(rootFileNames));
writeLog(" options: " + JSON.stringify(compilerOptions));
- var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program;
+ var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
hasChangedCompilerOptions = false;
hasChangedConfigFileParsingErrors = false;
resolutionCache.startCachingPerDirectoryResolution();
@@ -91475,10 +93317,10 @@
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
}
function isFileMissingOnHost(hostSourceFile) {
- return typeof hostSourceFile === "number";
+ return typeof hostSourceFile === "boolean";
}
- function isFilePresentOnHost(hostSourceFile) {
- return !!hostSourceFile.sourceFile;
+ function isFilePresenceUnknownOnHost(hostSourceFile) {
+ return typeof hostSourceFile.version === "boolean";
}
function fileExists(fileName) {
var path = toPath(fileName);
@@ -91496,36 +93338,32 @@
return undefined;
}
// Create new source file if requested or the versions dont match
- if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) {
+ if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
if (hostSourceFile) {
- if (shouldCreateNewSourceFile) {
- hostSourceFile.version++;
- }
if (sourceFile) {
// Set the source file and create file watcher now that file was present on the disk
hostSourceFile.sourceFile = sourceFile;
- sourceFile.version = hostSourceFile.version.toString();
+ hostSourceFile.version = sourceFile.version;
if (!hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */);
}
}
else {
// There is no source file on host any more, close the watch, missing file paths will track it
- if (isFilePresentOnHost(hostSourceFile)) {
+ if (hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher.close();
}
- sourceFilesCache.set(path, hostSourceFile.version);
+ sourceFilesCache.set(path, false);
}
}
else {
if (sourceFile) {
- sourceFile.version = initialVersion.toString();
var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */);
- sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher });
+ sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
}
else {
- sourceFilesCache.set(path, initialVersion);
+ sourceFilesCache.set(path, false);
}
}
return sourceFile;
@@ -91537,16 +93375,16 @@
if (hostSourceFile !== undefined) {
if (isFileMissingOnHost(hostSourceFile)) {
// The next version, lets set it as presence unknown file
- sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 });
+ sourceFilesCache.set(path, { version: false });
}
else {
- hostSourceFile.version++;
+ hostSourceFile.version = false;
}
}
}
function getSourceVersion(path) {
var hostSourceFile = sourceFilesCache.get(path);
- return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString();
+ return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
}
function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
@@ -91554,7 +93392,7 @@
// remove the cached entry.
// Note we arent deleting entry if file became missing in new program or
// there was version update and new source file was created.
- if (hostSourceFileInfo) {
+ if (hostSourceFileInfo !== undefined) {
// record the missing file paths so they can be removed later if watchers arent tracking them
if (isFileMissingOnHost(hostSourceFileInfo)) {
(missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
@@ -91643,7 +93481,7 @@
function onSourceFileChange(fileName, eventKind, path) {
updateCachedSystemWithFile(fileName, path, eventKind);
// Update the source file cache
- if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) {
+ if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
resolutionCache.invalidateResolutionOfFile(path);
}
resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
@@ -91687,7 +93525,7 @@
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
nextSourceFileVersion(fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
// 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
@@ -91741,16 +93579,23 @@
* This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
*/
UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
- UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream";
- UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate";
- UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked";
- UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream";
+ /**
+ * The project appears out of date because its upstream inputs are newer than its outputs,
+ * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
+ * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
+ */
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
+ UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
+ UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
+ UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
+ UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
+ UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
/**
* Projects with no outputs (i.e. "solution" files)
*/
- UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly";
+ UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
})(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
function createFileMap(toPath) {
// tslint:disable-next-line:no-null-keyword
@@ -91798,61 +93643,6 @@
function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
}
- 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);
- return ts.changeExtension(outputPath, ".d.ts" /* Dts */);
- }
- ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
- function getOutputJSFileName(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);
- 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) {
- // 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 = [];
- var js = getOutputJSFileName(inputFileName, configFile);
- outputs.push(js);
- if (configFile.options.sourceMap) {
- outputs.push(js + ".map");
- }
- 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");
- }
- }
- return outputs;
- }
- function getOutFileOutputs(project) {
- var out = project.options.outFile || project.options.out;
- if (!out) {
- return ts.Debug.fail("outFile must be set");
- }
- var outputs = [];
- outputs.push(out);
- if (project.options.sourceMap) {
- outputs.push(out + ".map");
- }
- if (ts.getEmitDeclarations(project.options)) {
- var dts = ts.changeExtension(out, ".d.ts" /* Dts */);
- outputs.push(dts);
- if (project.options.declarationMap) {
- outputs.push(dts + ".map");
- }
- }
- return outputs;
- }
- function rootDirOfOptions(opts, configFileName) {
- return opts.rootDir || ts.getDirectoryPath(configFileName);
- }
function newer(date1, date2) {
return date2 > date1 ? date2 : date1;
}
@@ -91872,7 +93662,7 @@
ts.createBuilderStatusReporter = createBuilderStatusReporter;
function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
var host = ts.createProgramHost(system, createProgram);
- host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; };
+ host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
@@ -91881,14 +93671,14 @@
}
function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
host.reportErrorSummary = reportErrorSummary;
return host;
}
ts.createSolutionBuilderHost = createSolutionBuilderHost;
function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
var watchHost = ts.createWatchHost(system, reportWatchStatus);
ts.copyProperties(host, watchHost);
return host;
@@ -91920,9 +93710,8 @@
var readFileWithCache = function (f) { return host.readFile(f); };
var projectCompilerOptions = baseCompilerOptions;
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; });
- var originalGetSourceFile = compilerHost.getSourceFile;
- var computeHash = host.createHash || ts.generateDjb2Hash;
- updateGetSourceFile();
+ ts.setGetSourceFileAsHashVersioned(compilerHost, host);
+ var buildInfoChecked = createFileMap(toPath);
// Watch state
var builderPrograms = createFileMap(toPath);
var diagnostics = createFileMap(toPath);
@@ -91960,6 +93749,7 @@
projectStatus.clear();
missingRoots.clear();
globalDependencyGraph = undefined;
+ buildInfoChecked.clear();
diagnostics.clear();
projectPendingBuild.clear();
projectErrorsReported.clear();
@@ -91974,29 +93764,6 @@
ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); });
ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher);
builderPrograms.clear();
- updateGetSourceFile();
- }
- function updateGetSourceFile() {
- if (options.watch) {
- if (compilerHost.getSourceFile === originalGetSourceFile) {
- compilerHost.getSourceFile = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
- if (result && options.watch) {
- result.version = computeHash.call(host, result.text);
- }
- return result;
- };
- }
- }
- else {
- if (compilerHost.getSourceFile !== originalGetSourceFile) {
- compilerHost.getSourceFile = originalGetSourceFile;
- }
- }
}
function isParsedCommandLine(entry) {
return !!entry.options;
@@ -92147,13 +93914,14 @@
newestInputFileTime = inputTime;
}
}
- // Collect the expected outputs of this project
- var outputs = getAllProjectOutputs(project);
- if (outputs.length === 0) {
+ // Container if no files are specified in the project
+ if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) {
return {
type: UpToDateStatusType.ContainerOnly
};
}
+ // Collect the expected outputs of this project
+ var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
// Now see if all outputs are newer than the newest input
var oldestOutputFileName = "(none)";
var oldestOutputFileTime = maximumDate;
@@ -92228,6 +93996,8 @@
upstreamProjectName: ref.path
};
}
+ // Check oldest output file name only if there is no missing output file name
+ if (!missingOutputFileName) {
// 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) {
@@ -92249,6 +94019,7 @@
};
}
}
+ }
if (missingOutputFileName !== undefined) {
return {
type: UpToDateStatusType.OutputMissing,
@@ -92262,9 +94033,33 @@
newerInputFileName: newestInputFileName
};
}
+ else {
+ // Check tsconfig time
+ var configStatus = checkConfigFileUpToDateStatus(project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
+ if (configStatus)
+ return configStatus;
+ // Check extended config time
+ var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName); });
+ if (extendedConfigStatus)
+ return extendedConfigStatus;
+ }
+ if (!buildInfoChecked.hasKey(project.options.configFilePath)) {
+ buildInfoChecked.setValue(project.options.configFilePath, true);
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath) {
+ var value = readFileWithCache(buildInfoPath);
+ var buildInfo = value && ts.getBuildInfo(value);
+ if (buildInfo && buildInfo.version !== ts.version) {
+ return {
+ type: UpToDateStatusType.TsVersionOutputOfDate,
+ version: buildInfo.version
+ };
+ }
+ }
+ }
if (usesPrepend && pseudoUpToDate) {
return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
+ type: UpToDateStatusType.OutOfDateWithPrepend,
outOfDateOutputFileName: oldestOutputFileName,
newerProjectName: upstreamChangedProject
};
@@ -92280,6 +94075,17 @@
oldestOutputFileName: oldestOutputFileName
};
}
+ function checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName) {
+ // Check tsconfig time
+ var tsconfigTime = host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
+ if (oldestOutputFileTime < tsconfigTime) {
+ return {
+ type: UpToDateStatusType.OutOfDateWithSelf,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerInputFileName: configFile
+ };
+ }
+ }
function invalidateProject(configFileName, reloadLevel) {
invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel);
}
@@ -92398,7 +94204,9 @@
updateOutputTimestamps(proj);
return;
}
- var buildResult = buildSingleProject(resolved);
+ var buildResult = needsBuild(status, resolved) ?
+ buildSingleProject(resolved) : // Actual build
+ updateBundle(resolved); // Fake that files have been built by manipulating prepend and existing output
if (buildResult & BuildResultFlags.AnyErrors)
return;
var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue;
@@ -92414,18 +94222,27 @@
// If declaration output is changed, build the project
// otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
var status_1 = projectStatus.getValue(project);
- if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
- if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) {
+ if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
+ if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status_1.type === UpToDateStatusType.OutOfDateWithPrepend)) {
projectStatus.setValue(project, {
type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: status_1.oldestOutputFileName,
+ outOfDateOutputFileName: status_1.type === UpToDateStatusType.OutOfDateWithPrepend ? status_1.outOfDateOutputFileName : status_1.oldestOutputFileName,
newerProjectName: resolved
});
}
}
else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) {
+ if (prepend) {
+ projectStatus.setValue(project, {
+ type: UpToDateStatusType.OutOfDateWithPrepend,
+ outOfDateOutputFileName: status_1.oldestOutputFileName,
+ newerProjectName: resolved
+ });
+ }
+ else {
status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
}
+ }
addProjToQueue(project);
}
}
@@ -92481,8 +94298,7 @@
}
if (options.verbose)
reportStatus(ts.Diagnostics.Building_project_0, proj);
- var resultFlags = BuildResultFlags.None;
- resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
+ var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
var configFile = parseConfigFile(proj);
if (!configFile) {
// Failed to read the config file
@@ -92498,8 +94314,7 @@
}
// TODO: handle resolve module name to cache result in project reference redirect
projectCompilerOptions = configFile.options;
- var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences);
- projectCompilerOptions = baseCompilerOptions;
+ var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, getOldProgram(proj, configFile), configFile.errors, configFile.projectReferences);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
@@ -92555,17 +94370,19 @@
var status = {
type: UpToDateStatusType.UpToDate,
newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime,
- oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile)
+ oldestOutputFileName: outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(configFile, !host.useCaseSensitiveFileNames())
};
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
}
}
@@ -92578,15 +94395,71 @@
builderPrograms.setValue(proj, program);
}
}
+ function getOldProgram(proj, parsed) {
+ if (options.force)
+ return undefined;
+ var value = builderPrograms.getValue(proj);
+ if (value)
+ return value;
+ return ts.readBuilderProgram(parsed.options, readFileWithCache);
+ }
+ function updateBundle(proj) {
+ if (options.dry) {
+ reportStatus(ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
+ return BuildResultFlags.Success;
+ }
+ if (options.verbose)
+ reportStatus(ts.Diagnostics.Updating_output_of_project_0, proj);
+ // Update js, and source map
+ var config = ts.Debug.assertDefined(parseConfigFile(proj));
+ projectCompilerOptions = config.options;
+ var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) { return parseConfigFile(resolveProjectName(ref.path)); });
+ if (ts.isString(outputFiles)) {
+ reportStatus(ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
+ return buildSingleProject(proj);
+ }
+ // Actual Emit
+ ts.Debug.assert(!!outputFiles.length);
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ var emittedOutputs = createFileMap(toPath);
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
+ emittedOutputs.setValue(name, true);
+ ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
+ });
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
+ reportAndStoreErrors(proj, emitDiagnostics);
+ projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
+ }
+ // Update timestamps for dts
+ var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
+ oldestOutputFileName: outputFiles[0].name
+ };
+ diagnostics.removeKey(proj);
+ projectStatus.setValue(proj, status);
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged;
+ }
function updateOutputTimestamps(proj) {
if (options.dry) {
- return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
+ return reportStatus(ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
}
var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
- projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
+ oldestOutputFileName: ts.getFirstProjectOutput(proj, !host.useCaseSensitiveFileNames())
+ };
+ projectStatus.setValue(proj.options.configFilePath, status);
}
function updateOutputTimestampsWorker(proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
- var outputs = getAllProjectOutputs(proj);
+ var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
if (!skipOutputs || outputs.length !== skipOutputs.getSize()) {
if (options.verbose) {
reportStatus(verboseMessage, proj.options.configFilePath);
@@ -92620,7 +94493,7 @@
reportParseConfigFileDiagnostic(proj);
continue;
}
- var outputs = getAllProjectOutputs(parsed);
+ var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) {
var output = outputs_3[_b];
if (host.fileExists(output)) {
@@ -92707,7 +94580,9 @@
// Do nothing
continue;
}
- var buildResult = buildSingleProject(next);
+ var buildResult = needsBuild(status, next) ?
+ buildSingleProject(next) : // Actual build
+ updateBundle(next); // Fake that files have been built by manipulating prepend and existing output
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
@@ -92720,6 +94595,15 @@
readFileWithCache = savedReadFileWithCache;
return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
}
+ function needsBuild(status, configFile) {
+ if (status.type !== UpToDateStatusType.OutOfDateWithPrepend || options.force)
+ return true;
+ var config = parseConfigFile(configFile);
+ return !config ||
+ config.fileNames.length === 0 ||
+ !!config.errors.length ||
+ !ts.isIncrementalCompilation(config.options);
+ }
function reportParseConfigFileDiagnostic(proj) {
reportAndStoreErrors(proj, [configFileCache.getValue(proj)]);
}
@@ -92759,33 +94643,6 @@
return ts.combinePaths(project, "tsconfig.json");
}
ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
- function getAllProjectOutputs(project) {
- if (project.options.outFile || project.options.out) {
- 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 getFirstProjectOutput(project) {
- if (project.options.outFile || project.options.out) {
- return ts.first(getOutFileOutputs(project));
- }
- for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
- var inputFile = _a[_i];
- var outputs = getOutputFileNames(inputFile, project);
- if (outputs.length) {
- return ts.first(outputs);
- }
- }
- return ts.Debug.fail("project " + project.options.configFilePath + " expected to have at least one output");
- }
function formatUpToDateStatus(configFileName, status, relName, formatMessage) {
switch (status.type) {
case UpToDateStatusType.OutOfDateWithSelf:
@@ -92800,6 +94657,8 @@
}
// Don't report anything for "up to date because it was already built" -- too verbose
break;
+ case UpToDateStatusType.OutOfDateWithPrepend:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(configFileName), relName(status.newerProjectName));
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:
@@ -92808,6 +94667,8 @@
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.TsVersionOutputOfDate:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(configFileName), status.version, ts.version);
case UpToDateStatusType.ContainerOnly:
// Don't report status on "solution" projects
case UpToDateStatusType.ComputingUpstream:
@@ -92983,6 +94844,11 @@
* typingsInstaller will run the command with `${npmLocation} install ...`.
*/
Arguments.NpmLocation = "--npmLocation";
+ /**
+ * Flag indicating that the typings installer should try to validate the default npm location.
+ * If the default npm is not found when this flag is enabled, fallback to `npm install`
+ */
+ Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
})(Arguments = server.Arguments || (server.Arguments = {}));
function hasArgument(argumentName) {
return ts.sys.args.indexOf(argumentName) >= 0;
@@ -93206,8 +95072,8 @@
if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
continue;
}
- var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- var packageJson = result_7.config;
+ 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.
@@ -93579,7 +95445,7 @@
/* @internal */
var ts;
(function (ts) {
- ts.scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true);
+ ts.scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ true);
var SemanticMeaning;
(function (SemanticMeaning) {
SemanticMeaning[SemanticMeaning["None"] = 0] = "None";
@@ -93614,7 +95480,7 @@
case 242 /* TypeAliasDeclaration */:
case 168 /* TypeLiteral */:
return 2 /* Type */;
- case 304 /* JSDocTypedefTag */:
+ case 309 /* 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 278 /* EnumMember */:
@@ -93639,14 +95505,14 @@
case 255 /* ExportDeclaration */:
return 7 /* All */;
// An external module can be a Value
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 4 /* Namespace */ | 1 /* Value */;
}
return 7 /* All */;
}
ts.getMeaningFromDeclaration = getMeaningFromDeclaration;
function getMeaningFromLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return 1 /* Value */;
}
else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) {
@@ -93852,7 +95718,7 @@
return undefined;
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
case 239 /* FunctionDeclaration */:
@@ -93870,7 +95736,7 @@
ts.getContainerNode = getContainerNode;
function getNodeKind(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */;
case 244 /* ModuleDeclaration */:
return "module" /* moduleElement */;
@@ -93879,8 +95745,8 @@
return "class" /* classElement */;
case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */;
case 242 /* TypeAliasDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return "type" /* typeElement */;
case 243 /* EnumDeclaration */: return "enum" /* enumElement */;
case 237 /* VariableDeclaration */:
@@ -94297,8 +96163,8 @@
isWhiteSpaceOnlyJsxText(child);
if (lookInPreviousChild) {
// actual start of the node is past the position - previous token should be at the end of previous child
- var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
- return candidate_2 && findRightmostToken(candidate_2, sourceFile);
+ var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
+ return candidate_1 && findRightmostToken(candidate_1, sourceFile);
}
else {
// candidate should be in this node
@@ -94306,7 +96172,7 @@
}
}
}
- ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
+ ts.Debug.assert(startNode !== undefined || n.kind === 284 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || 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.
@@ -94393,7 +96259,7 @@
}
ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute;
function isWhiteSpaceOnlyJsxText(node) {
- return ts.isJsxText(node) && node.containsOnlyWhiteSpaces;
+ return ts.isJsxText(node) && node.containsOnlyTriviaWhiteSpaces;
}
function isInTemplateString(sourceFile, position) {
var token = getTokenAtPosition(sourceFile, position);
@@ -95153,6 +97019,17 @@
return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName));
}
ts.getScriptKind = getScriptKind;
+ function getSymbolTarget(symbol) {
+ var next = symbol;
+ while (isTransientSymbol(next) && next.target) {
+ next = next.target;
+ }
+ return next;
+ }
+ ts.getSymbolTarget = getSymbolTarget;
+ function isTransientSymbol(symbol) {
+ return (symbol.flags & 33554432 /* Transient */) !== 0;
+ }
function getUniqueSymbolId(symbol, checker) {
return ts.getSymbolId(ts.skipAlias(symbol, checker));
}
@@ -95211,14 +97088,14 @@
ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext);
if (visited === node) {
// This only happens for leaf nodes - internal nodes always see their children change.
- var clone_8 = ts.getSynthesizedClone(node);
- if (ts.isStringLiteral(clone_8)) {
- clone_8.textSourceNode = node;
+ var clone_1 = ts.getSynthesizedClone(node);
+ if (ts.isStringLiteral(clone_1)) {
+ clone_1.textSourceNode = node;
}
- else if (ts.isNumericLiteral(clone_8)) {
- clone_8.numericLiteralFlags = node.numericLiteralFlags;
+ else if (ts.isNumericLiteral(clone_1)) {
+ clone_1.numericLiteralFlags = node.numericLiteralFlags;
}
- return ts.setTextRange(clone_8, node);
+ return ts.setTextRange(clone_1, node);
}
// PERF: As an optimization, rather than calling getSynthesizedClone, we'll update
// the new node created by visitEachChild with the extra changes getSynthesizedClone
@@ -95304,8 +97181,27 @@
return lastPos;
}
ts.getRenameLocation = getRenameLocation;
- function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
- ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
+ function copyLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyLeadingComments = copyLeadingComments;
+ function copyTrailingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticTrailingComment));
+ }
+ ts.copyTrailingComments = copyTrailingComments;
+ /**
+ * This function copies the trailing comments for the token that comes before `sourceNode`, as leading comments of `targetNode`.
+ * This is useful because sometimes a comment that refers to `sourceNode` will be a leading comment for `sourceNode`, according to the
+ * notion of trivia ownership, and instead will be a trailing comment for the token before `sourceNode`, e.g.:
+ * `function foo(\* not leading comment for a *\ a: string) {}`
+ * The comment refers to `a` but belongs to the `(` token, but we might want to copy it.
+ */
+ function copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyTrailingAsLeadingComments = copyTrailingAsLeadingComments;
+ function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, cb) {
+ return function (pos, end, kind, htnl) {
if (kind === 3 /* MultiLineCommentTrivia */) {
// Remove leading /*
pos += 2;
@@ -95316,10 +97212,9 @@
// Remove leading //
pos += 2;
}
- ts.addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
- });
+ cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
+ };
}
- ts.copyComments = copyComments;
function indexInTextChange(change, name) {
if (ts.startsWith(change, name))
return 0;
@@ -95400,11 +97295,35 @@
return checker.getTypeAtLocation(caseClause.parent.parent.expression);
}
ts.getSwitchedType = getSwitchedType;
+ function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
+ var checker = program.getTypeChecker();
+ var typeIsAccessible = true;
+ var notAccessible = function () { typeIsAccessible = false; };
+ var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
+ trackSymbol: function (symbol, declaration, meaning) {
+ // TODO: GH#18217
+ typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
+ },
+ reportInaccessibleThisError: notAccessible,
+ reportPrivateInBaseOfClassExpression: notAccessible,
+ reportInaccessibleUniqueSymbolError: notAccessible,
+ moduleResolverHost: {
+ readFile: host.readFile,
+ fileExists: host.fileExists,
+ directoryExists: host.directoryExists,
+ getSourceFiles: program.getSourceFiles,
+ getCurrentDirectory: program.getCurrentDirectory,
+ getCommonSourceDirectory: program.getCommonSourceDirectory,
+ }
+ });
+ return typeIsAccessible ? res : undefined;
+ }
+ ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible;
})(ts || (ts = {}));
var ts;
(function (ts) {
function createClassifier() {
- var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false);
+ var scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false);
function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) {
return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text);
}
@@ -95643,7 +97562,7 @@
var lastEnd = 0;
for (var i = 0; i < dense.length; i += 3) {
var start = dense[i];
- var length_5 = dense[i + 1];
+ var length_1 = dense[i + 1];
var type = dense[i + 2];
// Make a whitespace entry between the last item and this one.
if (lastEnd >= 0) {
@@ -95652,8 +97571,8 @@
entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace });
}
}
- entries.push({ length: length_5, classification: convertClassification(type) });
- lastEnd = start + length_5;
+ entries.push({ length: length_1, classification: convertClassification(type) });
+ lastEnd = start + length_1;
}
var whitespaceLength = text.length - lastEnd;
if (whitespaceLength > 0) {
@@ -95958,8 +97877,8 @@
var spanStart = span.start;
var spanLength = span.length;
// Make a scanner we can get trivia from.
- var triviaScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
- var mergeConflictScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
+ var triviaScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
+ var mergeConflictScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
var result = [];
processElement(sourceFile);
return { spans: result, endOfLineState: 0 /* None */ };
@@ -96051,18 +97970,18 @@
pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param"
pos = tag.tagName.end;
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
processJSDocParameterTag(tag);
break;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
processJSDocTemplateTag(tag);
pos = tag.end;
break;
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
@@ -96315,7 +98234,7 @@
return convertPathCompletions(completion.paths);
case 1 /* Properties */: {
var entries = [];
- Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary
+ Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 7 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries };
}
case 2 /* Types */: {
@@ -96366,6 +98285,7 @@
case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */;
case ".ts" /* Ts */: return ".ts" /* tsModifier */;
case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */;
+ case ".tsbuildinfo" /* TsBuildInfo */: return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported.");
case undefined: return "" /* none */;
default:
return ts.Debug.assertNever(extension);
@@ -96596,8 +98516,8 @@
* both foo.ts and foo.tsx become foo
*/
var foundFiles = ts.createMap(); // maps file to its extension
- for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
- var filePath = files_3[_i];
+ for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
+ var filePath = files_1[_i];
filePath = ts.normalizePath(filePath);
if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) {
continue;
@@ -96642,7 +98562,7 @@
continue;
var patterns = paths[path];
if (patterns) {
- var _loop_11 = function (name, kind, extension) {
+ var _loop_1 = function (name, kind, extension) {
// 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, extension));
@@ -96650,7 +98570,7 @@
};
for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) {
var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension;
- _loop_11(name, kind, extension);
+ _loop_1(name, kind, extension);
}
}
}
@@ -96685,7 +98605,7 @@
// (But do if we didn't find anything, e.g. 'package.json' missing.)
var foundGlobal = false;
if (fragmentDirectory === undefined) {
- var _loop_12 = function (moduleName) {
+ var _loop_2 = function (moduleName) {
if (!result.some(function (entry) { return entry.name === moduleName; })) {
foundGlobal = true;
result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined));
@@ -96693,7 +98613,7 @@
};
for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) {
var moduleName = _c[_b];
- _loop_12(moduleName);
+ _loop_2(moduleName);
}
}
if (!foundGlobal) {
@@ -96807,8 +98727,8 @@
// Check for typings specified in compiler options
var seen = ts.createMap();
var typeRoots = tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray;
- for (var _i = 0, typeRoots_2 = typeRoots; _i < typeRoots_2.length; _i++) {
- var root = typeRoots_2[_i];
+ for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
+ var root = typeRoots_1[_i];
getCompletionEntriesFromDirectories(root);
}
// Also get all @types typings installed in visible node_modules directories
@@ -96893,7 +98813,7 @@
var offset = index !== -1 ? index + 1 : 0;
// If the range is an identifier, span is unnecessary.
var length = text.length - offset;
- return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length);
+ return length === 0 || ts.isIdentifierText(text.substr(offset, length), 7 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length);
}
// Returns true if the path is explicitly relative to the script (i.e. relative to . or ..)
function isPathRelativeToScript(path) {
@@ -96978,6 +98898,7 @@
KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords";
KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords";
KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords";
+ KeywordCompletionFilters[KeywordCompletionFilters["Last"] = 6] = "Last";
})(KeywordCompletionFilters || (KeywordCompletionFilters = {}));
var GlobalsSearch;
(function (GlobalsSearch) {
@@ -97023,7 +98944,7 @@
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
}
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;
+ 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, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression;
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.
@@ -97054,7 +98975,7 @@
}
if (keywordFilters !== 0 /* None */) {
var entryNames = ts.arrayToSet(entries, function (e) { return e.name; });
- for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) {
var keywordEntry = _a[_i];
if (!entryNames.has(keywordEntry.name)) {
entries.push(keywordEntry);
@@ -97170,8 +99091,8 @@
// 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_3 = symbols; _i < symbols_3.length; _i++) {
- var symbol = symbols_3[_i];
+ for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
+ var symbol = symbols_1[_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) {
@@ -97390,7 +99311,7 @@
return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
}
function isModuleSymbol(symbol) {
- return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; });
+ return symbol.declarations.some(function (d) { return d.kind === 284 /* SourceFile */; });
}
function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) {
var typeChecker = program.getTypeChecker();
@@ -97441,11 +99362,11 @@
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
return { kind: 1 /* JsDocTagName */ };
}
- if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
currentToken = ts.getTokenAtPosition(sourceFile, position);
if (!currentToken ||
(!ts.isDeclarationName(currentToken) &&
- (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ ||
+ (currentToken.parent.kind !== 310 /* JSDocPropertyTag */ ||
currentToken.parent.name !== currentToken))) {
// Use as type location if inside tag's type expression
insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
@@ -97471,9 +99392,9 @@
// 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_3 = ts.timestamp();
+ var start_1 = ts.timestamp();
contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217
- log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_3));
+ log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1));
}
// Find the node where completion is requested on.
// Also determine whether we are trying to complete with members of that node
@@ -97498,6 +99419,14 @@
case 189 /* PropertyAccessExpression */:
propertyAccessToConvert = parent;
node = propertyAccessToConvert.expression;
+ if (node.end === contextToken.pos &&
+ ts.isCallExpression(node) &&
+ node.getChildCount(sourceFile) &&
+ ts.last(node.getChildren(sourceFile)).kind !== 21 /* CloseParenToken */) {
+ // This is likely dot from incorrectly parsed call expression and user is starting to write spread
+ // eg: Math.min(./**/)
+ return undefined;
+ }
break;
case 148 /* QualifiedName */:
node = parent.left;
@@ -97613,14 +99542,29 @@
var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker);
var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; });
var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker);
- 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 };
+ 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,
+ insideJsDocTagTypeExpression: insideJsDocTagTypeExpression
+ };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 304 /* JSDocTypedefTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 309 /* JSDocTypedefTag */:
return true;
default:
return false;
@@ -97660,7 +99604,9 @@
}
}
// 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 !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
+ if (!isTypeLocation &&
+ symbol.declarations &&
+ symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node));
}
return;
@@ -97793,8 +99739,8 @@
var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 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 !== 279 /* SourceFile */) {
- var thisType = typeChecker.tryGetThisTypeAt(scopeNode);
+ if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 284 /* SourceFile */) {
+ var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false);
if (thisType) {
for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) {
var symbol = _a[_i];
@@ -97826,7 +99772,7 @@
}
function isSnippetScope(scopeNode) {
switch (scopeNode.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 206 /* TemplateExpression */:
case 270 /* JsxExpression */:
case 218 /* Block */:
@@ -97885,6 +99831,8 @@
return parentKind === 242 /* TypeAliasDeclaration */;
case 119 /* AsKeyword */:
return parentKind === 212 /* AsExpression */;
+ case 86 /* ExtendsKeyword */:
+ return parentKind === 150 /* TypeParameter */;
}
}
return false;
@@ -98581,7 +100529,15 @@
}
return res;
});
- function getKeywordCompletions(keywordFilter) {
+ function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) {
+ if (!filterOutTsOnlyKeywords)
+ return getTypescriptKeywordCompletions(keywordFilter);
+ var index = keywordFilter + 6 /* Last */ + 1;
+ return _keywordCompletions[index] ||
+ (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter)
+ .filter(function (entry) { return !isTypeScriptOnlyKeyword(ts.stringToToken(entry.name)); }));
+ }
+ function getTypescriptKeywordCompletions(keywordFilter) {
return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) {
var kind = ts.stringToToken(entry.name);
switch (keywordFilter) {
@@ -98605,6 +100561,39 @@
}
}));
}
+ function isTypeScriptOnlyKeyword(kind) {
+ switch (kind) {
+ case 118 /* AbstractKeyword */:
+ case 120 /* AnyKeyword */:
+ case 146 /* BigIntKeyword */:
+ case 123 /* BooleanKeyword */:
+ case 125 /* DeclareKeyword */:
+ case 84 /* EnumKeyword */:
+ case 145 /* GlobalKeyword */:
+ case 109 /* ImplementsKeyword */:
+ case 127 /* InferKeyword */:
+ case 110 /* InterfaceKeyword */:
+ case 128 /* IsKeyword */:
+ case 129 /* KeyOfKeyword */:
+ case 130 /* ModuleKeyword */:
+ case 131 /* NamespaceKeyword */:
+ case 132 /* NeverKeyword */:
+ case 135 /* NumberKeyword */:
+ case 136 /* ObjectKeyword */:
+ case 113 /* PrivateKeyword */:
+ case 114 /* ProtectedKeyword */:
+ case 115 /* PublicKeyword */:
+ case 133 /* ReadonlyKeyword */:
+ case 138 /* StringKeyword */:
+ case 139 /* SymbolKeyword */:
+ case 140 /* TypeKeyword */:
+ case 142 /* UniqueKeyword */:
+ case 143 /* UnknownKeyword */:
+ return true;
+ default:
+ return false;
+ }
+ }
function isInterfaceOrTypeLiteralCompletionKeyword(kind) {
return kind === 133 /* ReadonlyKeyword */;
}
@@ -98658,7 +100647,7 @@
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 306 /* SyntaxList */:
+ case 311 /* 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);
@@ -98843,7 +100832,7 @@
var child = throwStatement;
while (child.parent) {
var parent = child.parent;
- if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) {
+ if (ts.isFunctionBlock(parent) || parent.kind === 284 /* SourceFile */) {
return parent;
}
// A throw-statement is only owned by a try-statement if the try-statement has
@@ -98901,7 +100890,7 @@
var container = declaration.parent;
switch (container.kind) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 271 /* CaseClause */:
case 272 /* DefaultClause */:
@@ -99399,7 +101388,7 @@
}
else if (!isAvailableThroughGlobal) {
var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
- ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
+ ts.Debug.assert(sourceFileLike.kind === 284 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
addIndirectUsers(sourceFileLike);
}
@@ -99508,7 +101497,7 @@
}
}
/**
- * `import x = require("./x") or `import * as x from "./x"`.
+ * `import x = require("./x")` or `import * as x from "./x"`.
* An `export =` may be imported by this syntax, so it may be a direct import.
* If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here.
*/
@@ -99565,10 +101554,10 @@
function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
var refs = [];
var checker = program.getTypeChecker();
- for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
- var referencingFile = sourceFiles_3[_i];
+ for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
+ var referencingFile = sourceFiles_1[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
- if (searchSourceFile.kind === 279 /* SourceFile */) {
+ if (searchSourceFile.kind === 284 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
var ref = _b[_a];
if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
@@ -99596,8 +101585,8 @@
/** 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_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
- var sourceFile = sourceFiles_4[_i];
+ for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
+ var sourceFile = sourceFiles_2[_i];
if (cancellationToken)
cancellationToken.throwIfCancellationRequested();
forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
@@ -99616,7 +101605,7 @@
}
/** 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 === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
+ return ts.forEach(sourceFileLike.kind === 284 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action));
});
}
@@ -99840,7 +101829,7 @@
return node.getSourceFile();
}
var parent = node.parent;
- if (parent.kind === 279 /* SourceFile */) {
+ if (parent.kind === 284 /* SourceFile */) {
return parent;
}
ts.Debug.assert(parent.kind === 245 /* ModuleBlock */);
@@ -99902,16 +101891,16 @@
}
FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition;
function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* 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 === 276 /* ShorthandPropertyAssignment */) {
- var result_8 = [];
- FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_8.push(nodeEntry(node)); });
- return result_8;
+ var result_1 = [];
+ FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); });
+ return result_1;
}
else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
@@ -99943,27 +101932,27 @@
case 0 /* Symbol */: {
var symbol = def.symbol;
var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
- var name_4 = 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_4, kind: kind_1, displayParts: displayParts_1 };
+ 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 };
}
case 1 /* Label */: {
- 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)] };
+ 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)] };
}
case 2 /* Keyword */: {
- var node_4 = def.node;
- var name_5 = ts.tokenToString(node_4.kind);
- return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] };
+ 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 */ }] };
}
case 3 /* This */: {
- 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 };
+ 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 };
}
case 4 /* String */: {
- 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)] };
+ 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)] };
}
default:
return ts.Debug.assertNever(def);
@@ -100122,8 +102111,8 @@
case 248 /* ImportEqualsDeclaration */:
case 253 /* ImportSpecifier */:
case 241 /* InterfaceDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
case 267 /* JsxAttribute */:
case 244 /* ModuleDeclaration */:
case 247 /* NamespaceExportDeclaration */:
@@ -100148,8 +102137,8 @@
return !!decl.initializer || ts.isCatchClause(decl.parent);
case 155 /* MethodSignature */:
case 153 /* PropertySignature */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
return false;
default:
return ts.Debug.failBadSyntaxKind(decl);
@@ -100241,7 +102230,7 @@
result = references;
continue;
}
- var _loop_13 = function (entry) {
+ var _loop_3 = function (entry) {
if (!entry.definition || entry.definition.type !== 0 /* Symbol */) {
result.push(entry);
return "continue";
@@ -100273,7 +102262,7 @@
};
for (var _b = 0, references_1 = references; _b < references_1.length; _b++) {
var entry = references_1[_b];
- _loop_13(entry);
+ _loop_3(entry);
}
}
return result;
@@ -100309,7 +102298,7 @@
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
switch (decl.kind) {
- case 279 /* SourceFile */:
+ case 284 /* 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 244 /* ModuleDeclaration */:
@@ -100382,11 +102371,16 @@
}
else {
var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] });
+ getReferencesInContainerOrFiles(symbol, state, search);
+ }
+ return result;
+ }
+ function getReferencesInContainerOrFiles(symbol, state, search) {
// Try to get the smallest valid scope that we can limit our search to;
// otherwise we'll need to search globally (i.e. include each file).
var scope = getSymbolScope(symbol);
if (scope) {
- getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope)));
+ getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(state.sourceFiles, scope)));
}
else {
// Global search
@@ -100397,8 +102391,6 @@
}
}
}
- return result;
- }
function getSpecialSearchKind(node) {
switch (node.kind) {
case 124 /* ConstructorKeyword */:
@@ -100450,9 +102442,7 @@
* Unlike `Search`, there is only one `State`.
*/
var State = /** @class */ (function () {
- function State(sourceFiles, sourceFilesSet,
- /** True if we're searching for constructor references. */
- specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
+ function State(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
this.sourceFiles = sourceFiles;
this.sourceFilesSet = sourceFilesSet;
this.specialSearchKind = specialSearchKind;
@@ -100533,8 +102523,8 @@
var sourceId = ts.getNodeId(sourceFile);
var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap());
var anyNewSymbols = false;
- for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) {
- var sym = symbols_4[_i];
+ for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
+ var sym = symbols_2[_i];
anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols;
}
return anyNewSymbols;
@@ -100673,14 +102663,14 @@
return undefined;
}
var scope;
- for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) {
- var declaration = declarations_11[_i];
+ for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
+ var declaration = declarations_1[_i];
var container = ts.getContainerNode(declaration);
if (scope && scope !== container) {
// Different declarations have different containers, bail out
return undefined;
}
- if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
+ if (!container || container.kind === 284 /* 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;
@@ -100725,8 +102715,8 @@
if (!signature.name || !ts.isIdentifier(signature.name))
return;
var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name));
- for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
- var sourceFile = sourceFiles_5[_i];
+ for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
+ var sourceFile = sourceFiles_3[_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)
@@ -100767,8 +102757,8 @@
// We found a match. Make sure it's not part of a larger word (i.e. the char
// before and after it have to be a non-identifier char).
var endPosition = position + symbolNameLength;
- if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 6 /* Latest */)) &&
- (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 6 /* Latest */))) {
+ if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 7 /* Latest */)) &&
+ (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 7 /* Latest */))) {
// Found a real match. Keep searching.
positions.push(position);
}
@@ -100917,7 +102907,9 @@
}
// For `export { foo as bar }`, rename `foo`, but not `bar`.
if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) {
- var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */;
+ var isDefaultExport = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */
+ || exportSpecifier.name.originalKeywordKind === 80 /* DefaultKeyword */;
+ var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */;
var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol);
var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker));
searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
@@ -101004,6 +102996,7 @@
var classExtending = tryGetClassByExtendingIdentifier(referenceLocation);
if (classExtending) {
findSuperConstructorAccesses(classExtending, pusher());
+ findInheritedConstructorReferences(classExtending, state);
}
}
}
@@ -101036,12 +103029,16 @@
* Reference the constructor and all calls to `new this()`.
*/
function findOwnConstructorReferences(classSymbol, sourceFile, addNode) {
- for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) {
+ var constructorSymbol = getClassConstructorSymbol(classSymbol);
+ if (constructorSymbol) {
+ for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile);
ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword);
addNode(ctrKeyword);
}
+ }
+ if (classSymbol.exports) {
classSymbol.exports.forEach(function (member) {
var decl = member.valueDeclaration;
if (decl && decl.kind === 156 /* MethodDeclaration */) {
@@ -101056,13 +103053,17 @@
}
});
}
+ }
+ function getClassConstructorSymbol(classSymbol) {
+ return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */);
+ }
/** Find references to `super` in the constructor of an extending class. */
- function findSuperConstructorAccesses(cls, addNode) {
- var ctr = cls.symbol.members.get("__constructor" /* Constructor */);
- if (!ctr) {
+ function findSuperConstructorAccesses(classDeclaration, addNode) {
+ var constructor = getClassConstructorSymbol(classDeclaration.symbol);
+ if (!constructor) {
return;
}
- for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) {
+ for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
ts.Debug.assert(decl.kind === 157 /* Constructor */);
var body = decl.body;
@@ -101075,6 +103076,16 @@
}
}
}
+ function hasOwnConstructor(classDeclaration) {
+ return !!getClassConstructorSymbol(classDeclaration.symbol);
+ }
+ function findInheritedConstructorReferences(classDeclaration, state) {
+ if (hasOwnConstructor(classDeclaration))
+ return;
+ var classSymbol = classDeclaration.symbol;
+ var search = state.createSearch(/*location*/ undefined, classSymbol, /*comingFrom*/ undefined);
+ getReferencesInContainerOrFiles(classSymbol, state, search);
+ }
function addImplementationReferences(refNode, addReference, state) {
// Check if we found a function/propertyAssignment/method with an implementation or initializer
if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) {
@@ -101239,7 +103250,7 @@
staticFlag &= ts.getModifierFlags(searchSpaceNode);
searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) {
return undefined;
}
@@ -101252,7 +103263,7 @@
default:
return undefined;
}
- var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
+ var references = ts.flatMap(searchSpaceNode.kind === 284 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) {
if (!ts.isThis(node)) {
@@ -101271,8 +103282,8 @@
// 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 279 /* SourceFile */:
- return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
+ case 284 /* SourceFile */:
+ return container.kind === 284 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
}
});
}).map(function (n) { return FindAllReferences.nodeEntry(n); });
@@ -101428,8 +103439,8 @@
// To achieve that we will keep iterating until the result stabilizes.
// Remember the last meaning
lastIterationMeaning = meaning;
- for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) {
- var declaration = declarations_12[_i];
+ for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
+ var declaration = declarations_2[_i];
var declarationMeaning = ts.getMeaningFromDeclaration(declaration);
if (declarationMeaning & meaning) {
meaning |= declarationMeaning;
@@ -101578,8 +103589,8 @@
// 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_5 = elements; _i < elements_5.length; _i++) {
- var element = elements_5[_i];
+ for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
+ var element = elements_1[_i];
foundExactMatch = tryUpdateString(element) || foundExactMatch;
}
return foundExactMatch;
@@ -101601,7 +103612,7 @@
}
function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) {
var allFiles = program.getSourceFiles();
- var _loop_14 = function (sourceFile) {
+ var _loop_4 = function (sourceFile) {
var newFromOld = oldToNew(sourceFile.path);
var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path;
var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath);
@@ -101633,7 +103644,7 @@
};
for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) {
var sourceFile = allFiles_1[_i];
- _loop_14(sourceFile);
+ _loop_4(sourceFile);
}
}
function combineNormal(pathA, pathB) {
@@ -101663,9 +103674,9 @@
return undefined;
// First try resolved module
if (resolved.resolvedModule) {
- var result_9 = tryChange(resolved.resolvedModule.resolvedFileName);
- if (result_9)
- return result_9;
+ var result_2 = tryChange(resolved.resolvedModule.resolvedFileName);
+ if (result_2)
+ return result_2;
}
// Then failed lookups except package.json since we dont want to touch them (only included ts/js files)
var result = ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson);
@@ -101775,10 +103786,10 @@
// bar<Test>(({pr/*goto*/op1})=>{});
if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) &&
(node === (parent.propertyName || parent.name))) {
- var name_6 = ts.getNameFromPropertyName(node);
+ var name_3 = ts.getNameFromPropertyName(node);
var type = typeChecker.getTypeAtLocation(parent.parent);
- return name_6 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) {
- var prop = t.getProperty(name_6);
+ 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);
});
}
@@ -102126,11 +104137,11 @@
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return [declaration];
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return [declaration, declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
@@ -102151,16 +104162,16 @@
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
var name = tag.name;
return name ? withNode(name) : comment;
default:
@@ -102371,7 +104382,7 @@
: undefined;
return { commentOwner: commentOwner, parameters: parameters_1 };
}
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return "quit";
case 244 /* ModuleDeclaration */:
// If in walking up the tree, we hit a a nested namespace declaration,
@@ -102423,7 +104434,7 @@
if (!patternMatcher)
return ts.emptyArray;
var rawItems = [];
- var _loop_15 = function (sourceFile) {
+ var _loop_5 = function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
if (excludeDtsFiles && sourceFile.isDeclarationFile) {
return "continue";
@@ -102433,9 +104444,9 @@
});
};
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
- for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
- var sourceFile = sourceFiles_6[_i];
- _loop_15(sourceFile);
+ for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
+ var sourceFile = sourceFiles_4[_i];
+ _loop_5(sourceFile);
}
rawItems.sort(compareNavigateToItems);
return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem);
@@ -102448,8 +104459,8 @@
if (!match) {
return; // continue to next named declarations
}
- for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) {
- var declaration = declarations_13[_i];
+ for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
+ var declaration = declarations_3[_i];
if (!shouldKeepItem(declaration, checker))
continue;
if (patternMatcher.patternContainsDots) {
@@ -102931,7 +104942,7 @@
}
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
var sourceFile = node;
return ts.isExternalModule(sourceFile)
? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\""
@@ -102983,10 +104994,10 @@
case 243 /* EnumDeclaration */:
case 241 /* InterfaceDeclaration */:
case 244 /* ModuleDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 242 /* TypeAliasDeclaration */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return true;
case 157 /* Constructor */:
case 156 /* MethodDeclaration */:
@@ -103007,7 +105018,7 @@
}
switch (navigationBarNodeKind(item.parent)) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
return true;
@@ -103092,7 +105103,7 @@
return !member.name || member.name.kind === 149 /* ComputedPropertyName */;
}
function getNodeSpan(node) {
- return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
+ return node.kind === 284 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
}
function getModifiers(node) {
if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) {
@@ -103213,8 +105224,8 @@
else {
// Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: false,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include,
suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
});
}
@@ -103228,7 +105239,7 @@
function removeUnusedImports(oldImports, sourceFile, program) {
var typeChecker = program.getTypeChecker();
var jsxNamespace = typeChecker.getJsxNamespace(sourceFile);
- var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */);
+ var jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */);
var usedImports = [];
for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) {
var importDecl = oldImports_1[_i];
@@ -103552,8 +105563,8 @@
var lastSingleLineCommentEnd = -1;
var singleLineCommentCount = 0;
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;
+ 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;
cancellationToken.throwIfCancellationRequested();
switch (kind) {
case 2 /* SingleLineCommentTrivia */:
@@ -103939,7 +105950,7 @@
if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
return true;
}
- if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) {
+ if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 7 /* Latest */)) {
return false;
}
// TODO: find a way to determine this for any unicode characters in a
@@ -103952,7 +105963,7 @@
if (ch >= 97 /* a */ && ch <= 122 /* z */) {
return true;
}
- if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) {
+ if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 7 /* Latest */)) {
return false;
}
// TODO: find a way to determine this for any unicode characters in a
@@ -103963,15 +105974,15 @@
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(str, value) {
var n = str.length - value.length;
- var _loop_16 = function (start) {
+ var _loop_6 = 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_1 = _loop_6(start);
+ if (typeof state_1 === "object")
+ return state_1.value;
}
return -1;
}
@@ -104982,7 +106993,7 @@
return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
}
function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) {
- var _loop_17 = function (n) {
+ var _loop_7 = 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); });
@@ -104992,9 +107003,9 @@
}
};
for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) {
- var state_5 = _loop_17(n);
- if (typeof state_5 === "object")
- return state_5.value;
+ var state_2 = _loop_7(n);
+ if (typeof state_2 === "object")
+ return state_2.value;
}
return undefined;
}
@@ -105069,13 +107080,13 @@
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); })));
+ var params = ts.createNodeArray(thisParameter.concat(checker.getExpandedParameters(candidateSignature).map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); })));
printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer);
});
return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) };
}
function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
- var isVariadic = candidateSignature.hasRestParameter;
+ var isVariadic = checker.hasEffectiveRestParameter(candidateSignature);
var printer = ts.createPrinter({ removeComments: true });
var typeParameterParts = ts.mapToDisplayParts(function (writer) {
if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) {
@@ -105083,7 +107094,7 @@
printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer);
}
});
- var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); });
+ var parameters = checker.getExpandedParameters(candidateSignature).map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); });
return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] };
}
function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) {
@@ -105272,8 +107283,8 @@
var name = importNameForConvertToDefaultImport(importNode);
if (!name)
continue;
- var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
- var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName);
+ var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
+ var resolvedFile = module && program.getSourceFile(module.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));
}
@@ -105288,8 +107299,8 @@
case 196 /* FunctionExpression */:
var decl = ts.getDeclarationOfExpando(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;
}
@@ -105726,7 +107737,7 @@
displayParts.push(ts.spacePart());
addFullSymbolName(symbol);
}
- if (symbolFlags & 1536 /* Module */) {
+ if (symbolFlags & 1536 /* Module */ && !isThisExpression) {
prefixNextMeaning();
var declaration = ts.getDeclarationOfKind(symbol, 244 /* ModuleDeclaration */);
var isNamespace = declaration && declaration.name && declaration.name.kind === 72 /* Identifier */;
@@ -105910,7 +107921,7 @@
// 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 === 279 /* SourceFile */; })) {
+ if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 284 /* SourceFile */; })) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) {
@@ -106035,7 +108046,7 @@
// 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 === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
+ if (parent.kind === 284 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
return false;
}
}
@@ -106149,7 +108160,7 @@
return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
});
options = ts.cloneCompilerOptions(options);
- var _loop_18 = function (opt) {
+ var _loop_8 = function (opt) {
if (!ts.hasProperty(options, opt.name)) {
return "continue";
}
@@ -106168,7 +108179,7 @@
};
for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
var opt = commandLineOptionsStringToEnum_1[_i];
- _loop_18(opt);
+ _loop_8(opt);
}
return options;
}
@@ -106264,8 +108275,8 @@
(function (ts) {
var formatting;
(function (formatting) {
- var standardScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
- var jsxScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */);
+ var standardScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
+ var jsxScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */);
var ScanAction;
(function (ScanAction) {
ScanAction[ScanAction["Scan"] = 0] = "Scan";
@@ -106859,7 +108870,7 @@
case 226 /* ForInStatement */:
// "in" keyword in [P in keyof T]: T[P]
case 150 /* TypeParameter */:
- return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */;
+ return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */ || context.currentTokenSpan.kind === 59 /* EqualsToken */ || context.nextTokenSpan.kind === 59 /* EqualsToken */;
// Technically, "of" is not a binary operator, but format it the same way as "in"
case 227 /* ForOfStatement */:
return context.currentTokenSpan.kind === 147 /* OfKeyword */ || context.nextTokenSpan.kind === 147 /* OfKeyword */;
@@ -107360,7 +109371,7 @@
case 244 /* ModuleDeclaration */:
var body = parent.body;
return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 245 /* ModuleBlock */:
return ts.rangeContainsRange(parent.statements, node);
@@ -108479,7 +110490,7 @@
// - 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 === 279 /* SourceFile */ || !parentAndChildShareLine);
+ (parent.kind === 284 /* SourceFile */ || !parentAndChildShareLine);
if (!useActualIndentation) {
return -1 /* Unknown */;
}
@@ -108567,7 +110578,7 @@
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return getList(node.typeParameters);
case 192 /* NewExpression */:
case 191 /* CallExpression */:
@@ -108816,11 +110827,23 @@
ts.Debug.assert(typeof end === "number");
n.__end = end;
}
- var Position;
- (function (Position) {
- Position[Position["FullStart"] = 0] = "FullStart";
- Position[Position["Start"] = 1] = "Start";
- })(Position = textChanges_3.Position || (textChanges_3.Position = {}));
+ var LeadingTriviaOption;
+ (function (LeadingTriviaOption) {
+ /** Exclude all leading trivia (use getStart()) */
+ LeadingTriviaOption[LeadingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include leading trivia and,
+ * if there are no line breaks between the node and the previous token,
+ * include all trivia between the node and the previous token
+ */
+ LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll";
+ })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {}));
+ var TrailingTriviaOption;
+ (function (TrailingTriviaOption) {
+ /** Exclude all trailing trivia (use getEnd()) */
+ TrailingTriviaOption[TrailingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include trailing trivia */
+ TrailingTriviaOption[TrailingTriviaOption["Include"] = 1] = "Include";
+ })(TrailingTriviaOption = textChanges_3.TrailingTriviaOption || (textChanges_3.TrailingTriviaOption = {}));
function skipWhitespacesAndLineBreaks(text, start) {
return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
@@ -108836,9 +110859,9 @@
}
return false;
}
- textChanges_3.useNonAdjustedPositions = {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: true,
+ var useNonAdjustedPositions = {
+ leadingTriviaOption: LeadingTriviaOption.Exclude,
+ trailingTriviaOption: TrailingTriviaOption.Exclude,
};
var ChangeKind;
(function (ChangeKind) {
@@ -108848,10 +110871,11 @@
ChangeKind[ChangeKind["Text"] = 3] = "Text";
})(ChangeKind || (ChangeKind = {}));
function getAdjustedRange(sourceFile, startNode, endNode, options) {
- return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) };
+ return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) };
}
- function getAdjustedStartPosition(sourceFile, node, options, position) {
- if (options.useNonAdjustedStartPosition) {
+ function getAdjustedStartPosition(sourceFile, node, options) {
+ var leadingTriviaOption = options.leadingTriviaOption;
+ if (leadingTriviaOption === LeadingTriviaOption.Exclude) {
return node.getStart(sourceFile);
}
var fullStart = node.getFullStart();
@@ -108869,7 +110893,7 @@
// fullstart
// when b is replaced - we usually want to keep the leading trvia
// when b is deleted - we delete it
- return position === Position.Start ? start : fullStart;
+ return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start;
}
// get start position of the line following the line that contains fullstart position
// (but only if the fullstart isn't the very beginning of the file)
@@ -108881,11 +110905,12 @@
}
function getAdjustedEndPosition(sourceFile, node, options) {
var end = node.end;
- if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
+ var trailingTriviaOption = options.trailingTriviaOption;
+ if (trailingTriviaOption === TrailingTriviaOption.Exclude || (ts.isExpression(node) && trailingTriviaOption !== TrailingTriviaOption.Include)) {
return end;
}
var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
- return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
+ return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)))
? newEnd
: end;
}
@@ -108930,15 +110955,15 @@
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 = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
- var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
+ var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
@@ -108946,11 +110971,11 @@
this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
};
ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
};
ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options);
};
ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
@@ -108958,14 +110983,14 @@
this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
};
ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
};
ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
- this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text);
+ this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text);
};
ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
@@ -108993,7 +111018,7 @@
};
ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) {
if (blankLineBetween === void 0) { blankLineBetween = false; }
- this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
+ this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
};
ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) {
var pos = before.getStart(sourceFile);
@@ -109100,7 +111125,7 @@
this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true));
};
ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) {
- var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start);
+ var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {});
this.insertNodeAt(sourceFile, pos, newNode, {
prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
suffix: this.newLineCharacter
@@ -109340,7 +111365,7 @@
ChangeTracker.prototype.finishDeleteDeclarations = function () {
var _this = this;
var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
- var _loop_19 = function (sourceFile, node) {
+ var _loop_9 = 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));
@@ -109353,7 +111378,7 @@
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_19(sourceFile, node);
+ _loop_9(sourceFile, node);
}
deletedNodesInLists.forEach(function (node) {
var sourceFile = node.getSourceFile();
@@ -109390,7 +111415,7 @@
textChanges_3.ChangeTracker = ChangeTracker;
// find first non-whitespace position in the leading trivia of the node
function startPositionToDeleteNodeInList(sourceFile, node) {
- return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
function getClassOrObjectBraceEnds(cls, sourceFile) {
return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end];
@@ -109410,14 +111435,14 @@
// 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_20 = function (i) {
+ var _loop_10 = 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_20(i);
+ _loop_10(i);
}
var textChanges = normalized.map(function (c) {
return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
@@ -109434,7 +111459,7 @@
function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) {
// TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this
var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter);
- var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind);
+ var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 7 /* ESNext */, /*setParentNodes*/ true, scriptKind);
var changes = ts.formatting.formatDocument(sourceFile, formatContext);
return applyChanges(nonFormattedText, changes) + newLineCharacter;
}
@@ -109727,7 +111752,7 @@
case 249 /* ImportDeclaration */:
deleteNode(changes, sourceFile, node,
// For first import, leave header comment in place
- node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined);
+ node === sourceFile.imports[0].parent ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined);
break;
case 186 /* BindingElement */:
var pattern = node.parent;
@@ -109765,7 +111790,7 @@
deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
}
else {
- deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined);
+ deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { trailingTriviaOption: TrailingTriviaOption.Exclude } : undefined);
}
}
}
@@ -109836,8 +111861,8 @@
/** 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);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, node, options);
var endPosition = getAdjustedEndPosition(sourceFile, node, options);
changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
}
@@ -110024,6 +112049,40 @@
(function (ts) {
var codefix;
(function (codefix) {
+ var fixId = "addNameToNamelessParameter";
+ var errorCodes = [ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_parameter_name, fixId, ts.Diagnostics.Add_names_to_all_parameters_without_names)];
+ },
+ fixIds: [fixId],
+ 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);
+ if (!ts.isIdentifier(token)) {
+ return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.formatSyntaxKind(token.kind));
+ }
+ var param = token.parent;
+ if (!ts.isParameter(param)) {
+ return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.formatSyntaxKind(token.kind));
+ }
+ var i = param.parent.parameters.indexOf(param);
+ ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one.");
+ ts.Debug.assert(i > -1, "Parameter not found in parent parameter list.");
+ var replacement = ts.createParameter(
+ /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer);
+ changeTracker.replaceNode(sourceFile, token, replacement);
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
var fixId = "annotateWithTypeFromJSDoc";
var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code];
codefix.registerCodeFix({
@@ -110096,18 +112155,18 @@
}
function transformJSDocType(node) {
switch (node.kind) {
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 164 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -110131,7 +112190,7 @@
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
+ var isRest = node.type.kind === 295 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
var name = node.name || (isRest ? "rest" : "arg" + index);
var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken;
return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
@@ -110287,7 +112346,7 @@
}
if (ts.isPropertyAccessExpression(parent)) {
var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken);
- var typeNode = getTypeNodeIfAccessible(type, parent, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host);
if (typeNode) {
// Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags
var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ "");
@@ -110391,7 +112450,7 @@
}
}
function annotate(changes, sourceFile, declaration, type, program, host) {
- var typeNode = getTypeNodeIfAccessible(type, declaration, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host);
if (typeNode) {
if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) {
var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration;
@@ -110417,7 +112476,7 @@
// only infer parameters that have (1) no type and (2) an accessible inferred type
if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name))
return;
- var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host);
+ var typeNode = inference.type && ts.getTypeNodeIfAccessible(inference.type, param, program, host);
var name = ts.getSynthesizedClone(param.name);
ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), "");
@@ -110434,47 +112493,33 @@
return !!merged;
}); });
var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray((oldTags || ts.emptyArray).concat(unmergedNewTags)));
- changes.insertJsdocCommentBefore(sourceFile, parent, tag);
+ var jsDocNode = parent.kind === 197 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent;
+ jsDocNode.jsDoc = parent.jsDoc;
+ jsDocNode.jsDocCache = parent.jsDocCache;
+ changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag);
+ }
+ function getJsDocNodeForArrowFunction(signature) {
+ if (signature.parent.kind === 154 /* PropertyDeclaration */) {
+ return signature.parent;
+ }
+ return signature.parent.parent;
}
function tryMergeJsdocTags(oldTag, newTag) {
if (oldTag.kind !== newTag.kind) {
return undefined;
}
switch (oldTag.kind) {
- case 299 /* JSDocParameterTag */: {
+ case 304 /* JSDocParameterTag */: {
var oldParam = oldTag;
var newParam = newTag;
return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText
? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment)
: undefined;
}
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment);
}
}
- function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
- var checker = program.getTypeChecker();
- var typeIsAccessible = true;
- var notAccessible = function () { typeIsAccessible = false; };
- var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
- trackSymbol: function (symbol, declaration, meaning) {
- // TODO: GH#18217
- typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
- },
- reportInaccessibleThisError: notAccessible,
- reportPrivateInBaseOfClassExpression: notAccessible,
- reportInaccessibleUniqueSymbolError: notAccessible,
- moduleResolverHost: {
- readFile: host.readFile,
- fileExists: host.fileExists,
- directoryExists: host.directoryExists,
- getSourceFiles: program.getSourceFiles,
- getCurrentDirectory: program.getCurrentDirectory,
- getCommonSourceDirectory: program.getCommonSourceDirectory,
- }
- });
- return typeIsAccessible ? res : undefined;
- }
function getReferences(token, program, cancellationToken) {
// Position shouldn't matter since token is not a SourceFile.
return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) {
@@ -110773,8 +112818,8 @@
}
function removeLowPriorityInferences(inferences, priorities) {
var toRemove = [];
- for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
- var i = inferences_2[_i];
+ for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
+ var i = inferences_1[_i];
for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) {
var _b = priorities_1[_a], high = _b.high, low = _b.low;
if (high(i)) {
@@ -110866,8 +112911,8 @@
types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); }));
if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) {
var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217
- var types_19 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); });
- types_19.push(checker.createPromiseType(types_19.length ? checker.getUnionType(types_19, 2 /* Subtype */) : checker.getAnyType()));
+ var types_1 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); });
+ types_1.push(checker.createPromiseType(types_1.length ? checker.getUnionType(types_1, 2 /* Subtype */) : checker.getAnyType()));
}
else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) {
types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)));
@@ -110876,7 +112921,7 @@
types.push(checker.createArrayType(recur(usageContext.numberIndexContext)));
}
else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) {
- var members_6 = ts.createUnderscoreEscapedMap();
+ var members_1 = ts.createUnderscoreEscapedMap();
var callSignatures = [];
var constructSignatures = [];
var stringIndexInfo = void 0;
@@ -110884,7 +112929,7 @@
usageContext.properties.forEach(function (context, name) {
var symbol = checker.createSymbol(4 /* Property */, name);
symbol.type = recur(context);
- members_6.set(name, symbol);
+ members_1.set(name, symbol);
});
}
if (usageContext.callContexts) {
@@ -110902,7 +112947,7 @@
if (usageContext.stringIndexContext) {
stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false);
}
- types.push(checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217
+ types.push(checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217
}
return types;
function recur(innerContext) {
@@ -110987,7 +113032,7 @@
precedingNode = ctorDeclaration.parent.parent;
newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
if (ctorDeclaration.parent.declarations.length === 1) {
- ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
+ ts.copyLeadingComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
changes.delete(sourceFile, precedingNode);
}
else {
@@ -110998,7 +113043,7 @@
if (!newClassDeclaration) {
return undefined;
}
- ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile);
+ ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile);
// Because the preceding node could be touched, we need to insert nodes before delete nodes.
changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
function createClassElementsFromSymbol(symbol) {
@@ -111051,7 +113096,7 @@
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
case 197 /* ArrowFunction */: {
@@ -111069,7 +113114,7 @@
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
default: {
@@ -111079,7 +113124,7 @@
}
var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
/*type*/ undefined, assignmentBinaryExpression.right);
- ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
return prop;
}
}
@@ -111171,7 +113216,7 @@
var newNodes = transformExpression(node, transformer, node);
changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes);
}
- var _loop_21 = function (statement) {
+ var _loop_11 = function (statement) {
ts.forEachChild(statement, function visit(node) {
if (ts.isCallExpression(node)) {
startTransformation(node, statement);
@@ -111183,7 +113228,7 @@
};
for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) {
var statement = returnStatements_1[_i];
- _loop_21(statement);
+ _loop_11(statement);
}
}
function getReturnStatementsWithPromiseHandlers(body) {
@@ -111508,8 +113553,8 @@
if (innerCbBody.length > 0) {
return innerCbBody;
}
- var type_6 = transformer.checker.getTypeAtLocation(func);
- var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType();
+ var type_1 = transformer.checker.getTypeAtLocation(func);
+ var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType();
var rightHandSide = ts.getSynthesizedDeepClone(funcBody);
var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide;
if (!shouldReturn) {
@@ -112835,7 +114880,7 @@
});
typeDeclToMembers.forEach(function (infos, classDeclaration) {
var supers = getAllSupers(classDeclaration, checker);
- var _loop_22 = function (info) {
+ var _loop_12 = function (info) {
// If some superclass added this property, don't add it again.
if (supers.some(function (superClassOrInterface) {
var superInfos = typeDeclToMembers.get(superClassOrInterface);
@@ -112862,7 +114907,7 @@
};
for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
var info = infos_1[_i];
- _loop_22(info);
+ _loop_12(info);
}
});
}));
@@ -113040,6 +115085,40 @@
(function (ts) {
var codefix;
(function (codefix) {
+ var fixId = "addMissingNewOperator";
+ var errorCodes = [ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile, span = context.span;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingNewOperator(t, sourceFile, span); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_new_operator_to_call, fixId, ts.Diagnostics.Add_missing_new_operator_to_all_calls)];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ return addMissingNewOperator(changes, context.sourceFile, diag);
+ }); },
+ });
+ function addMissingNewOperator(changes, sourceFile, span) {
+ var call = ts.cast(findAncestorMatchingSpan(sourceFile, span), ts.isCallExpression);
+ var newExpression = ts.createNew(call.expression, call.typeArguments, call.arguments);
+ changes.replaceNode(sourceFile, call, newExpression);
+ }
+ function findAncestorMatchingSpan(sourceFile, span) {
+ var token = ts.getTokenAtPosition(sourceFile, span.start);
+ var end = ts.textSpanEnd(span);
+ while (token.end < end) {
+ token = token.parent;
+ }
+ return token;
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
var fixName = "fixCannotFindModule";
var fixIdInstallTypesPackage = "installTypesPackage";
var fixIdGenerateTypes = "generateTypes";
@@ -113325,6 +115404,32 @@
(function (ts) {
var codefix;
(function (codefix) {
+ var fixId = "enableExperimentalDecorators";
+ var errorCodes = [
+ 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.code
+ ];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var configFile = context.program.getCompilerOptions().configFile;
+ if (configFile === undefined) {
+ return undefined;
+ }
+ var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) { return makeChange(changeTracker, configFile); });
+ return [codefix.createCodeFixActionNoFixId(fixId, changes, ts.Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)];
+ },
+ fixIds: [fixId],
+ });
+ function makeChange(changeTracker, configFile) {
+ codefix.setJsonCompilerOptionValue(changeTracker, configFile, "experimentalDecorators", ts.createTrue());
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
var fixId = "extendsInterfaceBecomesImplements";
var errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code];
codefix.registerCodeFix({
@@ -113768,7 +115873,7 @@
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 === 286 /* JSDocNullableType */) {
+ if (typeNode.kind === 291 /* 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, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -113788,7 +115893,7 @@
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 291 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -114037,8 +116142,8 @@
outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences));
break;
}
- for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
- var signature = signatures_7[_i];
+ for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
+ var signature = signatures_1[_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));
}
@@ -114085,7 +116190,7 @@
ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined;
});
var contextualType = checker.getContextualType(call);
- var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker) || ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ var returnType = (inJs || !contextualType) ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker);
return ts.createMethod(
/*decorators*/ undefined,
/*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined,
@@ -114121,8 +116226,8 @@
var maxArgsSignature = signatures[0];
var minArgumentCount = signatures[0].minArgumentCount;
var someSigHasRestParameter = false;
- for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
- var sig = signatures_8[_i];
+ for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
+ var sig = signatures_2[_i];
minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount);
if (sig.hasRestParameter) {
someSigHasRestParameter = true;
@@ -114281,8 +116386,8 @@
ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport));
}
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"), {}); });
+ var sourceFile_1 = context.sourceFile;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_1, expr, ts.createPropertyAccess(expr, "default"), {}); });
fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member));
}
return fixes;
@@ -114420,6 +116525,7 @@
return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings));
}
ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText;
+ /* @internal */
var OutputKind;
(function (OutputKind) {
OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals";
@@ -114554,16 +116660,16 @@
}
}
function toPropertyName(name) {
- return ts.isIdentifierText(name, 6 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name);
+ return ts.isIdentifierText(name, 7 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name);
}
// Parses assignments to "this.x" in the constructor into class property declarations
function getConstructorFunctionInstanceProperties(fnAst, members) {
forEachOwnNodeOfFunction(fnAst, function (node) {
if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) &&
ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) {
- var name_7 = node.left.name.text;
- if (!ts.isJsPrivate(name_7)) {
- ts.getOrUpdate(members, name_7, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_7, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); });
+ var name_4 = node.left.name.text;
+ if (!ts.isJsPrivate(name_4)) {
+ ts.getOrUpdate(members, name_4, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_4, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); });
}
}
});
@@ -114598,7 +116704,7 @@
}
function parseExpression(expr) {
var text = "const _ = " + expr;
- var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true);
+ var srcFile = ts.createSourceFile("test.ts", text, 7 /* Latest */, /*setParentNodes*/ true);
return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer;
}
function inferParameterType(_fn, _param) {
@@ -114615,7 +116721,7 @@
}
function isValidIdentifier(name) {
var keyword = ts.stringToToken(name);
- return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */);
+ return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 7 /* ESNext */);
}
function addComment(node, comment) {
if (comment !== undefined)
@@ -115070,7 +117176,7 @@
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 preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 7 /* 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);
@@ -115078,7 +117184,7 @@
});
var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName;
var neededNamedImports = [];
- var _loop_23 = function (element) {
+ var _loop_13 = 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);
@@ -115097,7 +117203,7 @@
};
for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) {
var element = _a[_i];
- _loop_23(element);
+ _loop_13(element);
}
changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName)));
if (neededNamedImports.length) {
@@ -115587,7 +117693,7 @@
// * Module/namespace or source file
if (isScope(current)) {
scopes.push(current);
- if (current.kind === 279 /* SourceFile */) {
+ if (current.kind === 284 /* SourceFile */) {
return scopes;
}
}
@@ -116152,8 +118258,8 @@
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_7 = members; _i < members_7.length; _i++) {
- var member = members_7[_i];
+ for (var _i = 0, members_2 = members; _i < members_2.length; _i++) {
+ var member = members_2[_i];
if (member.pos > maxPos) {
return prevMember || members[0];
}
@@ -116327,7 +118433,7 @@
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_24 = function (i) {
+ var _loop_14 = 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
@@ -116367,7 +118473,7 @@
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_24(i);
+ _loop_14(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
function isInGenericContext(node) {
@@ -116601,7 +118707,7 @@
function isBlockLike(node) {
switch (node.kind) {
case 218 /* Block */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 245 /* ModuleBlock */:
case 271 /* CaseClause */:
return true;
@@ -116918,10 +119024,10 @@
}
function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
var checker = program.getTypeChecker();
- var _loop_25 = function (sourceFile) {
+ var _loop_15 = function (sourceFile) {
if (sourceFile === oldFile)
return "continue";
- var _loop_26 = function (statement) {
+ var _loop_16 = function (statement) {
forEachImportInStatement(statement, function (importNode) {
if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol)
return;
@@ -116943,12 +119049,12 @@
};
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
var statement = _a[_i];
- _loop_26(statement);
+ _loop_16(statement);
}
};
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
- _loop_25(sourceFile);
+ _loop_15(sourceFile);
}
}
function getNamespaceLikeImport(node) {
@@ -116965,7 +119071,7 @@
}
}
function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) {
- var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */);
+ var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 7 /* ESNext */);
var needUniqueName = false;
var toChange = [];
ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) {
@@ -117063,9 +119169,9 @@
if (isTopLevelDeclarationStatement(statement) &&
!isExported(sourceFile, statement, useEs6Exports) &&
forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) {
- var exports_2 = addExport(statement, useEs6Exports);
- if (exports_2)
- return exports_2;
+ var exports = addExport(statement, useEs6Exports);
+ if (exports)
+ return exports;
}
return statement;
});
@@ -117191,7 +119297,7 @@
var movedSymbols = new SymbolSet();
var oldImportsNeededByNewFile = new SymbolSet();
var newFileImportsFromOldFile = new SymbolSet();
- var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 4 /* ContainsJsx */); });
+ var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 2 /* ContainsJsx */); });
var jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx);
if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code)
oldImportsNeededByNewFile.add(jsxNamespaceSymbol);
@@ -117225,7 +119331,7 @@
if (ts.contains(toMove, statement))
continue;
// jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile.
- if (jsxNamespaceSymbol && !!(statement.transformFlags & 4 /* ContainsJsx */)) {
+ if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) {
unusedImportsFromOldFile.delete(jsxNamespaceSymbol);
}
forEachReference(statement, checker, function (symbol) {
@@ -117540,13 +119646,13 @@
var returnStatement_1 = ts.createReturn(expression);
body = ts.createBlock([returnStatement_1], /* multiLine */ true);
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
+ ts.copyLeadingComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
}
else if (actionName === removeBracesActionName && returnStatement) {
var actualExpression = expression || ts.createVoidZero();
body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression;
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
+ ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
}
else {
ts.Debug.fail("invalid action");
@@ -117585,6 +119691,459 @@
})(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var convertParamsToDestructuredObject;
+ (function (convertParamsToDestructuredObject) {
+ var refactorName = "Convert parameters to destructured object";
+ var minimumParameterLength = 2;
+ refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
+ function getAvailableActions(context) {
+ var file = context.file, startPosition = context.startPosition;
+ var isJSFile = ts.isSourceFileJS(file);
+ if (isJSFile)
+ return ts.emptyArray; // TODO: GH#30113
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
+ if (!functionDeclaration)
+ return ts.emptyArray;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_parameters_to_destructured_object);
+ return [{
+ name: refactorName,
+ description: description,
+ actions: [{
+ name: refactorName,
+ description: description
+ }]
+ }];
+ }
+ function getEditsForAction(context, actionName) {
+ ts.Debug.assert(actionName === refactorName);
+ var file = context.file, startPosition = context.startPosition, program = context.program, cancellationToken = context.cancellationToken, host = context.host;
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker());
+ if (!functionDeclaration || !cancellationToken)
+ return undefined;
+ var groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken);
+ if (groupedReferences.valid) {
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(file, program, host, t, functionDeclaration, groupedReferences); });
+ return { renameFilename: undefined, renameLocation: undefined, edits: edits };
+ }
+ return { edits: [] }; // TODO: GH#30113
+ }
+ function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) {
+ var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); });
+ changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ",
+ // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
+ indentation: 0,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include
+ });
+ var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); });
+ for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) {
+ var call = functionCalls_1[_i];
+ if (call.arguments && call.arguments.length) {
+ var newArgument = ts.getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true);
+ changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include });
+ }
+ }
+ }
+ function getGroupedReferences(functionDeclaration, program, cancellationToken) {
+ var functionNames = getFunctionNames(functionDeclaration);
+ var classNames = ts.isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
+ var names = ts.deduplicate(functionNames.concat(classNames), ts.equateValues);
+ var checker = program.getTypeChecker();
+ var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); });
+ var groupedReferences = groupReferences(references);
+ if (!ts.every(groupedReferences.declarations, /*callback*/ function (/*callback*/ decl) { return ts.contains(names, decl); })) {
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ function groupReferences(referenceEntries) {
+ var classReferences = { accessExpressions: [], typeUsages: [] };
+ var groupedReferences = { functionCalls: [], declarations: [], classReferences: classReferences, valid: true };
+ var functionSymbols = ts.map(functionNames, checker.getSymbolAtLocation);
+ var classSymbols = ts.map(classNames, checker.getSymbolAtLocation);
+ var isConstructor = ts.isConstructorDeclaration(functionDeclaration);
+ for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
+ var entry = referenceEntries_1[_i];
+ if (entry.kind !== 1 /* Node */) {
+ groupedReferences.valid = false;
+ continue;
+ }
+ /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function.
+ Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test:
+ class A { foo(a: number, b: number) { return a + b; } }
+ class B { foo(c: number, d: number) { return c + d; } }
+ declare const ab: A | B;
+ ab.foo(1, 2);
+ Find all references will return `ab.foo(1, 2)` as a reference to A's `foo` but we could be calling B's `foo`.
+ When looking for constructor calls, however, the symbol on the constructor call reference is going to be the corresponding class symbol.
+ So we need to add a special case for this because when calling a constructor of a class through one of its subclasses,
+ the symbols are going to be different.
+ */
+ if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer) || ts.isNewExpressionTarget(entry.node)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var call = entryToFunctionCall(entry);
+ if (call) {
+ groupedReferences.functionCalls.push(call);
+ continue;
+ }
+ }
+ // if the refactored function is a constructor, we must also check if the references to its class are valid
+ if (isConstructor && ts.contains(classSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var accessExpression = entryToAccessExpression(entry);
+ if (accessExpression) {
+ classReferences.accessExpressions.push(accessExpression);
+ continue;
+ }
+ // Only class declarations are allowed to be used as a type (in a heritage clause),
+ // otherwise `findAllReferences` might not be able to track constructor calls.
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ var type = entryToType(entry);
+ if (type) {
+ classReferences.typeUsages.push(type);
+ continue;
+ }
+ }
+ }
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ }
+ }
+ function symbolComparer(a, b) {
+ return ts.getSymbolTarget(a) === ts.getSymbolTarget(b);
+ }
+ function entryToDeclaration(entry) {
+ if (ts.isDeclaration(entry.node.parent)) {
+ return entry.node;
+ }
+ return undefined;
+ }
+ function entryToFunctionCall(entry) {
+ if (entry.node.parent) {
+ var functionReference = entry.node;
+ var parent = functionReference.parent;
+ switch (parent.kind) {
+ // Function call (foo(...) or super(...))
+ case 191 /* CallExpression */:
+ var callExpression = ts.tryCast(parent, ts.isCallExpression);
+ if (callExpression && callExpression.expression === functionReference) {
+ return callExpression;
+ }
+ break;
+ // Constructor call (new Foo(...))
+ case 192 /* NewExpression */:
+ var newExpression = ts.tryCast(parent, ts.isNewExpression);
+ if (newExpression && newExpression.expression === functionReference) {
+ return newExpression;
+ }
+ break;
+ // Method call (x.foo(...))
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) {
+ var callExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_1 && callExpression_1.expression === propertyAccessExpression) {
+ return callExpression_1;
+ }
+ }
+ break;
+ // Method call (x["foo"](...))
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) {
+ var callExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_2 && callExpression_2.expression === elementAccessExpression) {
+ return callExpression_2;
+ }
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToAccessExpression(entry) {
+ if (entry.node.parent) {
+ var reference = entry.node;
+ var parent = reference.parent;
+ switch (parent.kind) {
+ // `C.foo`
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.expression === reference) {
+ return propertyAccessExpression;
+ }
+ break;
+ // `C["foo"]`
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.expression === reference) {
+ return elementAccessExpression;
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToType(entry) {
+ var reference = entry.node;
+ if (ts.getMeaningFromLocation(reference) === 2 /* Type */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) {
+ return reference;
+ }
+ return undefined;
+ }
+ function getFunctionDeclarationAtPosition(file, startPosition, checker) {
+ var node = ts.getTouchingToken(file, startPosition);
+ var functionDeclaration = ts.getContainingFunction(node);
+ // don't offer refactor on top-level JSDoc
+ if (isTopLevelJSDoc(node))
+ return undefined;
+ if (functionDeclaration
+ && isValidFunctionDeclaration(functionDeclaration, checker)
+ && ts.rangeContainsRange(functionDeclaration, node)
+ && !(functionDeclaration.body && ts.rangeContainsRange(functionDeclaration.body, node)))
+ return functionDeclaration;
+ return undefined;
+ }
+ function isTopLevelJSDoc(node) {
+ var containingJSDoc = ts.findAncestor(node, ts.isJSDocNode);
+ if (containingJSDoc) {
+ var containingNonJSDoc = ts.findAncestor(containingJSDoc, function (n) { return !ts.isJSDocNode(n); });
+ return !!containingNonJSDoc && ts.isFunctionLikeDeclaration(containingNonJSDoc);
+ }
+ return false;
+ }
+ function isValidFunctionDeclaration(functionDeclaration, checker) {
+ if (!isValidParameterNodeArray(functionDeclaration.parameters, checker))
+ return false;
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return !!functionDeclaration.name
+ && !!functionDeclaration.body
+ && !checker.isImplementationOfOverload(functionDeclaration);
+ case 157 /* Constructor */:
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ return !!functionDeclaration.body
+ && !!functionDeclaration.parent.name
+ && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ else {
+ return isValidVariableDeclaration(functionDeclaration.parent.parent)
+ && !!functionDeclaration.body
+ && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ case 196 /* FunctionExpression */:
+ case 197 /* ArrowFunction */:
+ return isValidVariableDeclaration(functionDeclaration.parent);
+ }
+ return false;
+ }
+ function isValidParameterNodeArray(parameters, checker) {
+ return getRefactorableParametersLength(parameters) >= minimumParameterLength
+ && ts.every(parameters, /*callback*/ function (/*callback*/ paramDecl) { return isValidParameterDeclaration(paramDecl, checker); });
+ }
+ function isValidParameterDeclaration(parameterDeclaration, checker) {
+ if (ts.isRestParameter(parameterDeclaration)) {
+ var type = checker.getTypeAtLocation(parameterDeclaration);
+ if (!checker.isArrayType(type) && !checker.isTupleType(type))
+ return false;
+ }
+ return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name);
+ }
+ function isValidVariableDeclaration(node) {
+ return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113
+ }
+ function hasThisParameter(parameters) {
+ return parameters.length > 0 && ts.isThis(parameters[0].name);
+ }
+ function getRefactorableParametersLength(parameters) {
+ if (hasThisParameter(parameters)) {
+ return parameters.length - 1;
+ }
+ return parameters.length;
+ }
+ function getRefactorableParameters(parameters) {
+ if (hasThisParameter(parameters)) {
+ parameters = ts.createNodeArray(parameters.slice(1), parameters.hasTrailingComma);
+ }
+ return parameters;
+ }
+ function createPropertyOrShorthandAssignment(name, initializer) {
+ if (ts.isIdentifier(initializer) && ts.getTextOfIdentifierOrLiteral(initializer) === name) {
+ return ts.createShorthandPropertyAssignment(name);
+ }
+ return ts.createPropertyAssignment(name, initializer);
+ }
+ function createNewArgument(functionDeclaration, functionArguments) {
+ var parameters = getRefactorableParameters(functionDeclaration.parameters);
+ var hasRestParameter = ts.isRestParameter(ts.last(parameters));
+ var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments;
+ var properties = ts.map(nonRestArguments, function (arg, i) {
+ var parameterName = getParameterName(parameters[i]);
+ var property = createPropertyOrShorthandAssignment(parameterName, arg);
+ ts.suppressLeadingAndTrailingTrivia(property.name);
+ if (ts.isPropertyAssignment(property))
+ ts.suppressLeadingAndTrailingTrivia(property.initializer);
+ copyComments(arg, property);
+ return property;
+ });
+ if (hasRestParameter && functionArguments.length >= parameters.length) {
+ var restArguments = functionArguments.slice(parameters.length - 1);
+ var restProperty = ts.createPropertyAssignment(getParameterName(ts.last(parameters)), ts.createArrayLiteral(restArguments));
+ properties.push(restProperty);
+ }
+ var objectLiteral = ts.createObjectLiteral(properties, /*multiLine*/ false);
+ return objectLiteral;
+ }
+ function createNewParameters(functionDeclaration, program, host) {
+ var checker = program.getTypeChecker();
+ var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters);
+ var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration);
+ var objectParameterName = ts.createObjectBindingPattern(bindingElements);
+ var objectParameterType = createParameterTypeNode(refactorableParameters);
+ var objectInitializer;
+ // If every parameter in the original function was optional, add an empty object initializer to the new object parameter
+ if (ts.every(refactorableParameters, isOptionalParameter)) {
+ objectInitializer = ts.createObjectLiteral();
+ }
+ var objectParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, objectParameterName,
+ /*questionToken*/ undefined, objectParameterType, objectInitializer);
+ if (hasThisParameter(functionDeclaration.parameters)) {
+ var thisParameter = functionDeclaration.parameters[0];
+ var newThisParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, thisParameter.name,
+ /*questionToken*/ undefined, thisParameter.type);
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.name);
+ copyComments(thisParameter.name, newThisParameter.name);
+ if (thisParameter.type) {
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.type);
+ copyComments(thisParameter.type, newThisParameter.type);
+ }
+ return ts.createNodeArray([newThisParameter, objectParameter]);
+ }
+ return ts.createNodeArray([objectParameter]);
+ function createBindingElementFromParameterDeclaration(parameterDeclaration) {
+ var element = ts.createBindingElement(
+ /*dotDotDotToken*/ undefined,
+ /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer);
+ ts.suppressLeadingAndTrailingTrivia(element);
+ if (parameterDeclaration.initializer && element.initializer) {
+ copyComments(parameterDeclaration.initializer, element.initializer);
+ }
+ return element;
+ }
+ function createParameterTypeNode(parameters) {
+ var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration);
+ var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */);
+ return typeNode;
+ }
+ function createPropertySignatureFromParameterDeclaration(parameterDeclaration) {
+ var parameterType = parameterDeclaration.type;
+ if (!parameterType && (parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration))) {
+ parameterType = getTypeNode(parameterDeclaration);
+ }
+ var propertySignature = ts.createPropertySignature(
+ /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType,
+ /*initializer*/ undefined);
+ ts.suppressLeadingAndTrailingTrivia(propertySignature);
+ copyComments(parameterDeclaration.name, propertySignature.name);
+ if (parameterDeclaration.type && propertySignature.type) {
+ copyComments(parameterDeclaration.type, propertySignature.type);
+ }
+ return propertySignature;
+ }
+ function getTypeNode(node) {
+ var type = checker.getTypeAtLocation(node);
+ return ts.getTypeNodeIfAccessible(type, node, program, host);
+ }
+ function isOptionalParameter(parameterDeclaration) {
+ if (ts.isRestParameter(parameterDeclaration)) {
+ var type = checker.getTypeAtLocation(parameterDeclaration);
+ return !checker.isTupleType(type);
+ }
+ return checker.isOptionalParameter(parameterDeclaration);
+ }
+ }
+ function copyComments(sourceNode, targetNode) {
+ var sourceFile = sourceNode.getSourceFile();
+ var text = sourceFile.text;
+ if (hasLeadingLineBreak(sourceNode, text)) {
+ ts.copyLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ else {
+ ts.copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ ts.copyTrailingComments(sourceNode, targetNode, sourceFile);
+ }
+ function hasLeadingLineBreak(node, text) {
+ var start = node.getFullStart();
+ var end = node.getStart();
+ for (var i = start; i < end; i++) {
+ if (text.charCodeAt(i) === 10 /* lineFeed */)
+ return true;
+ }
+ return false;
+ }
+ function getParameterName(paramDeclaration) {
+ return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name);
+ }
+ function getClassNames(constructorDeclaration) {
+ switch (constructorDeclaration.parent.kind) {
+ case 240 /* ClassDeclaration */:
+ var classDeclaration = constructorDeclaration.parent;
+ return [classDeclaration.name];
+ case 209 /* ClassExpression */:
+ var classExpression = constructorDeclaration.parent;
+ var variableDeclaration = constructorDeclaration.parent.parent;
+ var className = classExpression.name;
+ if (className)
+ return [className, variableDeclaration.name];
+ return [variableDeclaration.name];
+ }
+ }
+ function getFunctionNames(functionDeclaration) {
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return [functionDeclaration.name];
+ case 157 /* Constructor */:
+ var ctrKeyword = ts.findChildOfKind(functionDeclaration, 124 /* ConstructorKeyword */, functionDeclaration.getSourceFile());
+ if (functionDeclaration.parent.kind === 209 /* ClassExpression */) {
+ var variableDeclaration = functionDeclaration.parent.parent;
+ return [variableDeclaration.name, ctrKeyword];
+ }
+ return [ctrKeyword];
+ case 197 /* ArrowFunction */:
+ return [functionDeclaration.parent.name];
+ case 196 /* FunctionExpression */:
+ if (functionDeclaration.name)
+ return [functionDeclaration.name, functionDeclaration.parent.name];
+ return [functionDeclaration.parent.name];
+ default:
+ return ts.Debug.assertNever(functionDeclaration);
+ }
+ }
+ })(convertParamsToDestructuredObject = refactor.convertParamsToDestructuredObject || (refactor.convertParamsToDestructuredObject = {}));
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
var ts;
(function (ts) {
/** The version of the language service API */
@@ -117602,7 +120161,8 @@
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
- this.transformFlags = undefined; // TODO: GH#18217
+ this.modifierFlagsCache = 0 /* None */;
+ this.transformFlags = 0 /* None */;
this.parent = undefined;
this.kind = kind;
}
@@ -117664,7 +120224,7 @@
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 288 /* FirstJSDocNode */ || kid.kind > 310 /* LastJSDocNode */; });
return child.kind < 148 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -117734,11 +120294,11 @@
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(311 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
- for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) {
- var node = nodes_7[_i];
+ for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
+ var node = nodes_1[_i];
addSyntheticNodes(list._children, pos, node.pos, parent);
list._children.push(node);
pos = node.end;
@@ -117752,6 +120312,8 @@
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
+ this.modifierFlagsCache = 0 /* None */;
+ this.transformFlags = 0 /* None */;
this.parent = undefined;
}
TokenOrIdentifierObject.prototype.getSourceFile = function () {
@@ -117980,8 +120542,8 @@
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_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)
@@ -118327,7 +120889,7 @@
var sourceFile;
if (this.currentFileName !== fileName) {
// This is a new file, just parse it
- sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 6 /* Latest */, version, /*setNodeParents*/ true, scriptKind);
+ sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 7 /* Latest */, version, /*setNodeParents*/ true, scriptKind);
}
else if (this.currentFileVersion !== version) {
// This is the same file, just a newer version. Incrementally parse the file.
@@ -118451,9 +121013,9 @@
}());
ts.ThrottledCancellationToken = ThrottledCancellationToken;
function createLanguageService(host, documentRegistry, syntaxOnly) {
+ var _a;
if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); }
if (syntaxOnly === void 0) { syntaxOnly = false; }
- var _a;
var syntaxTreeCache = new SyntaxTreeCache(host);
var program;
var lastProjectVersion;
@@ -118484,7 +121046,7 @@
function getValidSourceFile(fileName) {
var sourceFile = program.getSourceFile(fileName);
if (!sourceFile) {
- throw new Error("Could not find file: '" + fileName + "'.");
+ throw new Error("Could not find sourceFile: '" + fileName + "' in " + (program && JSON.stringify(program.getSourceFiles().map(function (f) { return f.fileName; }))) + ".");
}
return sourceFile;
}
@@ -118733,14 +121295,14 @@
var typeChecker = program.getTypeChecker();
var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker);
if (!symbol || typeChecker.isUnknownSymbol(symbol)) {
- var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined;
- return type_7 && {
+ 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_7, ts.getContainerNode(node)); }),
- documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined,
- tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined
+ 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) {
@@ -120851,4 +123413,6 @@
// TODO: it should be moved into a namespace though.
/* @internal */
var toolsVersion = ts.versionMajorMinor;
-//# sourceMappingURL=typescriptServices.out.js.map
\ No newline at end of file
+
+
+//# sourceMappingURL=typescript.js.map

lib/typescriptServices.d.ts

@@ -14,7 +14,7 @@
***************************************************************************** */
declare namespace ts {
- const versionMajorMinor = "3.3";
+ const versionMajorMinor = "3.4";
/** The version of the TypeScript compiler release */
const version: string;
}
@@ -355,40 +355,45 @@
ShorthandPropertyAssignment = 276,
SpreadAssignment = 277,
EnumMember = 278,
- SourceFile = 279,
- Bundle = 280,
- UnparsedSource = 281,
- InputFiles = 282,
- JSDocTypeExpression = 283,
- JSDocAllType = 284,
- JSDocUnknownType = 285,
- JSDocNullableType = 286,
- JSDocNonNullableType = 287,
- JSDocOptionalType = 288,
- JSDocFunctionType = 289,
- JSDocVariadicType = 290,
- JSDocComment = 291,
- JSDocTypeLiteral = 292,
- JSDocSignature = 293,
- JSDocTag = 294,
- JSDocAugmentsTag = 295,
- JSDocClassTag = 296,
- JSDocCallbackTag = 297,
- JSDocEnumTag = 298,
- JSDocParameterTag = 299,
- JSDocReturnTag = 300,
- JSDocThisTag = 301,
- JSDocTypeTag = 302,
- JSDocTemplateTag = 303,
- JSDocTypedefTag = 304,
- JSDocPropertyTag = 305,
- SyntaxList = 306,
- NotEmittedStatement = 307,
- PartiallyEmittedExpression = 308,
- CommaListExpression = 309,
- MergeDeclarationMarker = 310,
- EndOfDeclarationMarker = 311,
- Count = 312,
+ UnparsedPrologue = 279,
+ UnparsedPrepend = 280,
+ UnparsedText = 281,
+ UnparsedInternalText = 282,
+ UnparsedSyntheticReference = 283,
+ SourceFile = 284,
+ Bundle = 285,
+ UnparsedSource = 286,
+ InputFiles = 287,
+ JSDocTypeExpression = 288,
+ JSDocAllType = 289,
+ JSDocUnknownType = 290,
+ JSDocNullableType = 291,
+ JSDocNonNullableType = 292,
+ JSDocOptionalType = 293,
+ JSDocFunctionType = 294,
+ JSDocVariadicType = 295,
+ JSDocComment = 296,
+ JSDocTypeLiteral = 297,
+ JSDocSignature = 298,
+ JSDocTag = 299,
+ JSDocAugmentsTag = 300,
+ JSDocClassTag = 301,
+ JSDocCallbackTag = 302,
+ JSDocEnumTag = 303,
+ JSDocParameterTag = 304,
+ JSDocReturnTag = 305,
+ JSDocThisTag = 306,
+ JSDocTypeTag = 307,
+ JSDocTemplateTag = 308,
+ JSDocTypedefTag = 309,
+ JSDocPropertyTag = 310,
+ SyntaxList = 311,
+ NotEmittedStatement = 312,
+ PartiallyEmittedExpression = 313,
+ CommaListExpression = 314,
+ MergeDeclarationMarker = 315,
+ EndOfDeclarationMarker = 316,
+ Count = 317,
FirstAssignment = 59,
LastAssignment = 71,
FirstCompoundAssignment = 60,
@@ -414,10 +419,10 @@
FirstBinaryOperator = 28,
LastBinaryOperator = 71,
FirstNode = 148,
- FirstJSDocNode = 283,
- LastJSDocNode = 305,
- FirstJSDocTagNode = 294,
- LastJSDocTagNode = 305
+ FirstJSDocNode = 288,
+ LastJSDocNode = 310,
+ FirstJSDocTagNode = 299,
+ LastJSDocTagNode = 310,
}
enum NodeFlags {
None = 0,
@@ -446,7 +451,7 @@
ReachabilityCheckFlags = 384,
ReachabilityAndEmitFlags = 1408,
ContextFlags = 12679168,
- TypeExcludesFlags = 20480
+ TypeExcludesFlags = 20480,
}
enum ModifierFlags {
None = 0,
@@ -814,7 +819,7 @@
}
interface TypeOperatorNode extends TypeNode {
kind: SyntaxKind.TypeOperator;
- operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword;
+ operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword;
type: TypeNode;
}
interface IndexedAccessTypeNode extends TypeNode {
@@ -997,6 +1002,14 @@
interface NoSubstitutionTemplateLiteral extends LiteralExpression {
kind: SyntaxKind.NoSubstitutionTemplateLiteral;
}
+ enum TokenFlags {
+ None = 0,
+ Scientific = 16,
+ Octal = 32,
+ HexSpecifier = 64,
+ BinarySpecifier = 128,
+ OctalSpecifier = 256,
+ }
interface NumericLiteral extends LiteralExpression {
kind: SyntaxKind.NumericLiteral;
}
@@ -1190,9 +1203,9 @@
dotDotDotToken?: Token<SyntaxKind.DotDotDotToken>;
expression?: Expression;
}
- interface JsxText extends Node {
+ interface JsxText extends LiteralLikeNode {
kind: SyntaxKind.JsxText;
- containsOnlyWhiteSpaces: boolean;
+ containsOnlyTriviaWhiteSpaces: boolean;
parent: JsxElement;
}
type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment;
@@ -1737,10 +1750,44 @@
}
interface UnparsedSource extends Node {
kind: SyntaxKind.UnparsedSource;
- fileName?: string;
+ fileName: string;
text: string;
+ prologues: ReadonlyArray<UnparsedPrologue>;
+ helpers: ReadonlyArray<UnscopedEmitHelper> | undefined;
+ referencedFiles: ReadonlyArray<FileReference>;
+ typeReferenceDirectives: ReadonlyArray<string> | undefined;
+ libReferenceDirectives: ReadonlyArray<FileReference>;
+ hasNoDefaultLib?: boolean;
sourceMapPath?: string;
sourceMapText?: string;
+ syntheticReferences?: ReadonlyArray<UnparsedSyntheticReference>;
+ texts: ReadonlyArray<UnparsedSourceText>;
+ }
+ type UnparsedSourceText = UnparsedPrepend | UnparsedTextLike;
+ type UnparsedNode = UnparsedPrologue | UnparsedSourceText | UnparsedSyntheticReference;
+ interface UnparsedSection extends Node {
+ kind: SyntaxKind;
+ data?: string;
+ parent: UnparsedSource;
+ }
+ interface UnparsedPrologue extends UnparsedSection {
+ kind: SyntaxKind.UnparsedPrologue;
+ data: string;
+ parent: UnparsedSource;
+ }
+ interface UnparsedPrepend extends UnparsedSection {
+ kind: SyntaxKind.UnparsedPrepend;
+ data: string;
+ parent: UnparsedSource;
+ texts: ReadonlyArray<UnparsedTextLike>;
+ }
+ interface UnparsedTextLike extends UnparsedSection {
+ kind: SyntaxKind.UnparsedText | SyntaxKind.UnparsedInternalText;
+ parent: UnparsedSource;
+ }
+ interface UnparsedSyntheticReference extends UnparsedSection {
+ kind: SyntaxKind.UnparsedSyntheticReference;
+ parent: UnparsedSource;
}
interface JsonSourceFile extends SourceFile {
statements: NodeArray<JsonObjectExpressionStatement>;
@@ -2014,7 +2061,7 @@
WriteTypeParametersOrArguments = 1,
UseOnlyExternalAliasing = 2,
AllowAnyNodeKind = 4,
- UseAliasDefinedOutsideCurrentScope = 8
+ UseAliasDefinedOutsideCurrentScope = 8,
}
enum TypePredicateKind {
This = 0,
@@ -2092,7 +2139,7 @@
ExportHasLocal = 944,
BlockScoped = 418,
PropertyOrAccessor = 98308,
- ClassMember = 106500
+ ClassMember = 106500,
}
interface Symbol {
flags: SymbolFlags;
@@ -2200,7 +2247,7 @@
Instantiable = 63176704,
StructuredOrInstantiable = 66846720,
Narrowable = 133970943,
- NotUnionOrUnit = 67637251
+ NotUnionOrUnit = 67637251,
}
type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
interface Type {
@@ -2247,7 +2294,7 @@
MarkerType = 8192,
JSLiteral = 16384,
FreshLiteral = 32768,
- ClassOrInterface = 3
+ ClassOrInterface = 3,
}
interface ObjectType extends Type {
objectFlags: ObjectFlags;
@@ -2286,6 +2333,7 @@
interface TupleType extends GenericType {
minLength: number;
hasRestElement: boolean;
+ readonly: boolean;
associatedNames?: __String[];
}
interface TupleTypeReference extends TypeReference {
@@ -2334,8 +2382,8 @@
root: ConditionalRoot;
checkType: Type;
extendsType: Type;
- resolvedTrueType?: Type;
- resolvedFalseType?: Type;
+ trueType: Type;
+ falseType: Type;
}
interface SubstitutionType extends InstantiableType {
typeVariable: TypeVariable;
@@ -2494,6 +2542,8 @@
reactNamespace?: string;
jsxFactory?: string;
composite?: boolean;
+ incremental?: boolean;
+ tsBuildInfoFile?: string;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -2570,9 +2620,10 @@
ES2016 = 3,
ES2017 = 4,
ES2018 = 5,
- ESNext = 6,
+ ES2019 = 6,
+ ESNext = 7,
JSON = 100,
- Latest = 6
+ Latest = 7
}
enum LanguageVariant {
Standard = 0,
@@ -2669,7 +2720,8 @@
Dts = ".d.ts",
Js = ".js",
Jsx = ".jsx",
- Json = ".json"
+ Json = ".json",
+ TsBuildInfo = ".tsbuildinfo"
}
interface ResolvedModuleWithFailedLookupLocations {
readonly resolvedModule: ResolvedModuleFull | undefined;
@@ -2742,7 +2794,7 @@
NoHoisting = 2097152,
HasEndOfDeclarationMarker = 4194304,
Iterator = 8388608,
- NoAsciiEscaping = 16777216
+ NoAsciiEscaping = 16777216,
}
interface EmitHelper {
readonly name: string;
@@ -2750,6 +2802,10 @@
readonly text: string | ((node: EmitHelperUniqueNameCallback) => string);
readonly priority?: number;
}
+ interface UnscopedEmitHelper extends EmitHelper {
+ readonly scoped: false;
+ readonly text: string;
+ }
type EmitHelperUniqueNameCallback = (name: string) => string;
enum EmitHint {
SourceFile = 0,
@@ -3359,6 +3415,7 @@
function isNewExpression(node: Node): node is NewExpression;
function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression;
function isTypeAssertion(node: Node): node is TypeAssertion;
+ function isConstTypeReference(node: Node): boolean;
function isParenthesizedExpression(node: Node): node is ParenthesizedExpression;
function skipPartiallyEmittedExpressions(node: Expression): Expression;
function skipPartiallyEmittedExpressions(node: Node): Node;
@@ -3448,6 +3505,9 @@
function isSourceFile(node: Node): node is SourceFile;
function isBundle(node: Node): node is Bundle;
function isUnparsedSource(node: Node): node is UnparsedSource;
+ function isUnparsedPrepend(node: Node): node is UnparsedPrepend;
+ function isUnparsedTextLike(node: Node): node is UnparsedTextLike;
+ function isUnparsedNode(node: Node): node is UnparsedNode;
function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression;
function isJSDocAllType(node: JSDocAllType): node is JSDocAllType;
function isJSDocUnknownType(node: Node): node is JSDocUnknownType;
@@ -3667,7 +3727,7 @@
function createLiteral(value: number | PseudoBigInt): NumericLiteral;
function createLiteral(value: boolean): BooleanLiteral;
function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression;
- function createNumericLiteral(value: string): NumericLiteral;
+ function createNumericLiteral(value: string, numericLiteralFlags?: TokenFlags): NumericLiteral;
function createBigIntLiteral(value: string): BigIntLiteral;
function createStringLiteral(text: string): StringLiteral;
function createRegularExpressionLiteral(text: string): RegularExpressionLiteral;
@@ -3759,7 +3819,7 @@
function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode;
function createThisTypeNode(): ThisTypeNode;
function createTypeOperatorNode(type: TypeNode): TypeOperatorNode;
- function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword, type: TypeNode): TypeOperatorNode;
+ function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword, type: TypeNode): TypeOperatorNode;
function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode;
function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
@@ -3932,6 +3992,10 @@
function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement;
function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement;
function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray<JsxChild>, closingFragment: JsxClosingFragment): JsxFragment;
+ function createJsxText(text: string, containsOnlyTriviaWhiteSpaces?: boolean): JsxText;
+ function updateJsxText(node: JsxText, text: string, containsOnlyTriviaWhiteSpaces?: boolean): JsxText;
+ function createJsxOpeningFragment(): JsxOpeningFragment;
+ function createJsxJsxClosingFragment(): JsxClosingFragment;
function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: ReadonlyArray<JsxChild>, closingFragment: JsxClosingFragment): JsxFragment;
function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute;
function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute;
@@ -3983,10 +4047,10 @@
function updateCommaList(node: CommaListExpression, elements: ReadonlyArray<Expression>): CommaListExpression;
function createBundle(sourceFiles: ReadonlyArray<SourceFile>, prepends?: ReadonlyArray<UnparsedSource | InputFiles>): Bundle;
function createUnparsedSourceFile(text: string): UnparsedSource;
- function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts"): UnparsedSource;
+ function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts", stripInternal?: boolean): UnparsedSource;
function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource;
function createInputFiles(javascriptText: string, declarationText: string): InputFiles;
- function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined): InputFiles;
+ function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined, buildInfoPath: string | undefined): InputFiles;
function createInputFiles(javascriptText: string, declarationText: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): InputFiles;
function updateBundle(node: Bundle, sourceFiles: ReadonlyArray<SourceFile>, prepends?: ReadonlyArray<UnparsedSource>): Bundle;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray<Statement>): CallExpression;

lib/typescriptServices.js

@@ -73,9 +73,9 @@
(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.3";
+ ts.versionMajorMinor = "3.4";
/** The version of the TypeScript compiler release */
- ts.version = ts.versionMajorMinor + ".4000";
+ ts.version = ts.versionMajorMinor + ".5";
})(ts || (ts = {}));
(function (ts) {
/* @internal */
@@ -131,19 +131,25 @@
// Keep the class inside a function so it doesn't get compiled if it's not used.
function shimMap() {
var MapIterator = /** @class */ (function () {
- function MapIterator(data, selector) {
- this.index = 0;
- this.data = data;
+ function MapIterator(currentEntry, selector) {
+ this.currentEntry = currentEntry;
this.selector = selector;
- this.keys = Object.keys(data);
}
MapIterator.prototype.next = function () {
- var index = this.index;
- if (index < this.keys.length) {
- this.index++;
- return { value: this.selector(this.data, this.keys[index]), done: false };
+ // Navigate to the next entry.
+ while (this.currentEntry) {
+ var skipNext = !!this.currentEntry.skipNext;
+ this.currentEntry = this.currentEntry.nextEntry;
+ if (!skipNext) {
+ break;
+ }
}
+ if (this.currentEntry) {
+ return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false };
+ }
+ else {
return { value: undefined, done: true };
+ }
};
return MapIterator;
}());
@@ -151,15 +157,36 @@
function class_1() {
this.data = createDictionaryObject();
this.size = 0;
+ // Create a first (stub) map entry that will not contain a key
+ // and value but serves as starting point for iterators.
+ this.firstEntry = {};
+ // When the map is empty, the last entry is the same as the
+ // first one.
+ this.lastEntry = this.firstEntry;
}
class_1.prototype.get = function (key) {
- return this.data[key];
+ var entry = this.data[key];
+ return entry && entry.value;
};
class_1.prototype.set = function (key, value) {
if (!this.has(key)) {
this.size++;
+ // Create a new entry that will be appended at the
+ // end of the linked list.
+ var newEntry = {
+ key: key,
+ value: value
+ };
+ this.data[key] = newEntry;
+ // Adjust the references.
+ var previousLastEntry = this.lastEntry;
+ previousLastEntry.nextEntry = newEntry;
+ newEntry.previousEntry = previousLastEntry;
+ this.lastEntry = newEntry;
+ }
+ else {
+ this.data[key].value = value;
}
- this.data[key] = value;
return this;
};
class_1.prototype.has = function (key) {
@@ -169,7 +196,28 @@
class_1.prototype.delete = function (key) {
if (this.has(key)) {
this.size--;
+ var entry = this.data[key];
delete this.data[key];
+ // Adjust the linked list references of the neighbor entries.
+ var previousEntry = entry.previousEntry;
+ previousEntry.nextEntry = entry.nextEntry;
+ if (entry.nextEntry) {
+ entry.nextEntry.previousEntry = previousEntry;
+ }
+ // When the deleted entry was the last one, we need to
+ // adust the lastEntry reference.
+ if (this.lastEntry === entry) {
+ this.lastEntry = previousEntry;
+ }
+ // Adjust the forward reference of the deleted entry
+ // in case an iterator still references it. This allows us
+ // to throw away the entry, but when an active iterator
+ // (which points to the current entry) continues, it will
+ // navigate to the entry that originally came before the
+ // current one and skip it.
+ entry.previousEntry = undefined;
+ entry.nextEntry = previousEntry;
+ entry.skipNext = true;
return true;
}
return false;
@@ -177,24 +225,46 @@
class_1.prototype.clear = function () {
this.data = createDictionaryObject();
this.size = 0;
+ // Reset the linked list. Note that we must adjust the forward
+ // references of the deleted entries to ensure iterators stuck
+ // in the middle of the list don't continue with deleted entries,
+ // but can continue with new entries added after the clear()
+ // operation.
+ var firstEntry = this.firstEntry;
+ var currentEntry = firstEntry.nextEntry;
+ while (currentEntry) {
+ var nextEntry = currentEntry.nextEntry;
+ currentEntry.previousEntry = undefined;
+ currentEntry.nextEntry = firstEntry;
+ currentEntry.skipNext = true;
+ currentEntry = nextEntry;
+ }
+ firstEntry.nextEntry = undefined;
+ this.lastEntry = firstEntry;
};
class_1.prototype.keys = function () {
- return new MapIterator(this.data, function (_data, key) { return key; });
+ return new MapIterator(this.firstEntry, function (key) { return key; });
};
class_1.prototype.values = function () {
- return new MapIterator(this.data, function (data, key) { return data[key]; });
+ return new MapIterator(this.firstEntry, function (_key, value) { return value; });
};
class_1.prototype.entries = function () {
- return new MapIterator(this.data, function (data, key) { return [key, data[key]]; });
+ return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; });
};
class_1.prototype.forEach = function (action) {
- for (var key in this.data) {
- action(this.data[key], key);
+ var iterator = this.entries();
+ while (true) {
+ var _a = iterator.next(), entry = _a.value, done = _a.done;
+ if (done) {
+ break;
+ }
+ action(entry[1], entry[0]);
}
};
return class_1;
}());
}
+ ts.shimMap = shimMap;
function length(array) {
return array ? array.length : 0;
}
@@ -742,7 +812,7 @@
}
/**
* Deduplicates an unsorted array.
- * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates.
+ * @param equalityComparer An `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`.
*/
@@ -958,6 +1028,21 @@
} };
}
ts.arrayIterator = arrayIterator;
+ function arrayReverseIterator(array) {
+ var i = array.length;
+ return {
+ next: function () {
+ if (i === 0) {
+ return { value: undefined, done: true };
+ }
+ else {
+ i--;
+ return { value: array[i], done: false };
+ }
+ }
+ };
+ }
+ ts.arrayReverseIterator = arrayReverseIterator;
/**
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
*/
@@ -1168,9 +1253,11 @@
}
for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
var arg = args_1[_a];
+ if (arg === undefined)
+ continue;
for (var p in arg) {
if (hasProperty(arg, p)) {
- t[p] = arg[p]; // TODO: GH#23368
+ t[p] = arg[p];
}
}
}
@@ -1346,6 +1433,9 @@
/** Do nothing and return true */
function returnTrue() { return true; }
ts.returnTrue = returnTrue;
+ /** Do nothing and return undefined */
+ function returnUndefined() { return undefined; }
+ ts.returnUndefined = returnUndefined;
/** Returns its argument. */
function identity(x) { return x; }
ts.identity = identity;
@@ -1492,7 +1582,7 @@
Debug.assertEachDefined = assertEachDefined;
function assertNever(member, message, stackCrawlMark) {
if (message === void 0) { message = "Illegal value:"; }
- var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member);
+ var detail = typeof member === "object" && "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member);
return fail(message + " " + detail, stackCrawlMark || assertNever);
}
Debug.assertNever = assertNever;
@@ -2795,47 +2885,53 @@
SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment";
// Enum
SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember";
+ // Unparsed
+ SyntaxKind[SyntaxKind["UnparsedPrologue"] = 279] = "UnparsedPrologue";
+ SyntaxKind[SyntaxKind["UnparsedPrepend"] = 280] = "UnparsedPrepend";
+ SyntaxKind[SyntaxKind["UnparsedText"] = 281] = "UnparsedText";
+ SyntaxKind[SyntaxKind["UnparsedInternalText"] = 282] = "UnparsedInternalText";
+ SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 283] = "UnparsedSyntheticReference";
// Top-level nodes
- SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile";
- SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle";
- SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource";
- SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles";
+ SyntaxKind[SyntaxKind["SourceFile"] = 284] = "SourceFile";
+ SyntaxKind[SyntaxKind["Bundle"] = 285] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 286] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 287] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 288] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 289] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature";
- SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag";
- SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 290] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 291] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 292] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 293] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 294] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 295] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 296] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 297] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocSignature"] = 298] = "JSDocSignature";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 299] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 300] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 301] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 302] = "JSDocCallbackTag";
+ SyntaxKind[SyntaxKind["JSDocEnumTag"] = 303] = "JSDocEnumTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 304] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 305] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocThisTag"] = 306] = "JSDocThisTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 307] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 308] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 309] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 310] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 311] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 312] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 313] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 314] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 315] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 316] = "EndOfDeclarationMarker";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 312] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 317] = "Count";
// Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment";
@@ -2862,10 +2958,10 @@
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator";
SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 288] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 310] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 299] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 310] = "LastJSDocTagNode";
/* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword";
/* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
@@ -2972,21 +3068,27 @@
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
})(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
- /* @internal */
var TokenFlags;
(function (TokenFlags) {
TokenFlags[TokenFlags["None"] = 0] = "None";
+ /* @internal */
TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
+ /* @internal */
TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
+ /* @internal */
TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
+ /* @internal */
TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
+ /* @internal */
TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
+ /* @internal */
TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
+ /* @internal */
TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
})(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
var FlowFlags;
@@ -3346,12 +3448,6 @@
TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
/* @internal */
- TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType";
- /* @internal */
- TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral";
- /* @internal */
- TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType";
- /* @internal */
TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
/* @internal */
TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
@@ -3383,28 +3479,29 @@
TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive";
TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable";
TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable";
+ /* @internal */
+ TypeFlags[TypeFlags["ObjectFlagsType"] = 3899392] = "ObjectFlagsType";
// 'Narrowable' types are types where narrowing actually narrows.
// This *should* be every type other than null, undefined, void, and never
TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable";
TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit";
/* @internal */
TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion";
+ // The following flags are aggregated during union and intersection type construction
/* @internal */
- TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening";
- /* @internal */
- TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags";
+ TypeFlags[TypeFlags["IncludesMask"] = 1835007] = "IncludesMask";
// The following flags are used for different purposes during union and intersection type construction
/* @internal */
- TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType";
+ TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
/* @internal */
- TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard";
+ TypeFlags[TypeFlags["IncludesNonWideningType"] = 2097152] = "IncludesNonWideningType";
/* @internal */
- TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject";
+ TypeFlags[TypeFlags["IncludesWildcard"] = 4194304] = "IncludesWildcard";
/* @internal */
- TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags";
+ TypeFlags[TypeFlags["IncludesEmptyObject"] = 8388608] = "IncludesEmptyObject";
// The following flag is used for different purposes by maybeTypeOfKind
/* @internal */
- TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType";
+ TypeFlags[TypeFlags["GenericMappedType"] = 131072] = "GenericMappedType";
})(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
var ObjectFlags;
(function (ObjectFlags) {
@@ -3424,7 +3521,19 @@
ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
+ /* @internal */
+ ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion";
+ /* @internal */
+ ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType";
+ /* @internal */
+ ObjectFlags[ObjectFlags["ContainsObjectLiteral"] = 262144] = "ContainsObjectLiteral";
+ /* @internal */
+ ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType";
ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
+ /* @internal */
+ ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening";
+ /* @internal */
+ ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags";
})(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
/* @internal */
var Variance;
@@ -3469,6 +3578,7 @@
InferenceFlags[InferenceFlags["None"] = 0] = "None";
InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
+ InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
})(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
/**
* Ternary values are defined such that
@@ -3576,9 +3686,10 @@
ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
- ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext";
+ ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
+ ScriptTarget[ScriptTarget["ESNext"] = 7] = "ESNext";
ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
- ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest";
+ ScriptTarget[ScriptTarget["Latest"] = 7] = "Latest";
})(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
var LanguageVariant;
(function (LanguageVariant) {
@@ -3727,6 +3838,7 @@
Extension["Js"] = ".js";
Extension["Jsx"] = ".jsx";
Extension["Json"] = ".json";
+ Extension["TsBuildInfo"] = ".tsbuildinfo";
})(Extension = ts.Extension || (ts.Extension = {}));
/* @internal */
var TransformFlags;
@@ -3734,71 +3846,69 @@
TransformFlags[TransformFlags["None"] = 0] = "None";
// Facts
// - Flags used to indicate that a node or subtree contains syntax that requires transformation.
- TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript";
- TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript";
- TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx";
- TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext";
- TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017";
- TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016";
- TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015";
+ TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
+ TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
+ TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
+ TransformFlags[TransformFlags["ContainsES2019"] = 8] = "ContainsES2019";
+ TransformFlags[TransformFlags["ContainsES2018"] = 16] = "ContainsES2018";
+ TransformFlags[TransformFlags["ContainsES2017"] = 32] = "ContainsES2017";
+ TransformFlags[TransformFlags["ContainsES2016"] = 64] = "ContainsES2016";
TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015";
- TransformFlags[TransformFlags["Generator"] = 256] = "Generator";
- TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
- TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment";
- TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment";
+ TransformFlags[TransformFlags["ContainsGenerator"] = 256] = "ContainsGenerator";
+ TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 512] = "ContainsDestructuringAssignment";
// Markers
// - Flags used to indicate that a subtree contains a specific transformation.
- TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax";
- TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis";
- TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis";
- TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName";
- TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments";
- TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread";
- TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread";
- TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName";
- TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding";
- TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern";
- TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield";
- TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion";
- TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport";
- TransformFlags[TransformFlags["Super"] = 33554432] = "Super";
- TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper";
+ TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 1024] = "ContainsTypeScriptClassSyntax";
+ TransformFlags[TransformFlags["ContainsLexicalThis"] = 2048] = "ContainsLexicalThis";
+ TransformFlags[TransformFlags["ContainsRestOrSpread"] = 4096] = "ContainsRestOrSpread";
+ TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 8192] = "ContainsObjectRestOrSpread";
+ TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 16384] = "ContainsComputedPropertyName";
+ TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 32768] = "ContainsBlockScopedBinding";
+ TransformFlags[TransformFlags["ContainsBindingPattern"] = 65536] = "ContainsBindingPattern";
+ TransformFlags[TransformFlags["ContainsYield"] = 131072] = "ContainsYield";
+ TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 262144] = "ContainsHoistedDeclarationOrCompletion";
+ TransformFlags[TransformFlags["ContainsDynamicImport"] = 524288] = "ContainsDynamicImport";
// Please leave this as 1 << 29.
// It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
// It is a good reminder of how much room we have left
TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
// Assertions
// - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
- TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript";
- TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx";
- TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext";
- TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017";
- TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016";
- TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015";
- TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator";
- TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment";
+ TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
+ TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
+ TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
+ TransformFlags[TransformFlags["AssertES2019"] = 8] = "AssertES2019";
+ TransformFlags[TransformFlags["AssertES2018"] = 16] = "AssertES2018";
+ TransformFlags[TransformFlags["AssertES2017"] = 32] = "AssertES2017";
+ TransformFlags[TransformFlags["AssertES2016"] = 64] = "AssertES2016";
+ TransformFlags[TransformFlags["AssertES2015"] = 128] = "AssertES2015";
+ TransformFlags[TransformFlags["AssertGenerator"] = 256] = "AssertGenerator";
+ TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 512] = "AssertDestructuringAssignment";
// Scope Exclusions
// - Bitmasks that exclude flags from propagating out of a specific context
// into the subtree flags of their container.
- TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes";
- TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes";
- TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes";
- TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes";
- TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes";
- TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes";
- TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes";
- TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes";
- TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes";
- TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes";
- TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes";
- TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes";
- TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes";
- TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes";
- TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes";
- TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes";
+ TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
+ TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
+ TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
+ TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 537371648] = "ArrowFunctionExcludes";
+ TransformFlags[TransformFlags["FunctionExcludes"] = 537373696] = "FunctionExcludes";
+ TransformFlags[TransformFlags["ConstructorExcludes"] = 537372672] = "ConstructorExcludes";
+ TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 537372672] = "MethodOrAccessorExcludes";
+ TransformFlags[TransformFlags["PropertyExcludes"] = 536872960] = "PropertyExcludes";
+ TransformFlags[TransformFlags["ClassExcludes"] = 536888320] = "ClassExcludes";
+ TransformFlags[TransformFlags["ModuleExcludes"] = 537168896] = "ModuleExcludes";
+ TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
+ TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536896512] = "ObjectLiteralExcludes";
+ TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536875008] = "ArrayLiteralOrCallOrNewExcludes";
+ TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 536944640] = "VariableDeclarationListExcludes";
+ TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
+ TransformFlags[TransformFlags["CatchClauseExcludes"] = 536879104] = "CatchClauseExcludes";
+ TransformFlags[TransformFlags["BindingPatternExcludes"] = 536875008] = "BindingPatternExcludes";
+ // Propagating flags
+ // - Bitmasks for flags that should propagate from a child
+ TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 2048] = "PropertyNamePropagatingFlags";
// Masks
// - Additional bitmasks
- TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask";
})(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
var EmitFlags;
(function (EmitFlags) {
@@ -3880,6 +3990,20 @@
EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
})(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
+ /*@internal*/
+ var BundleFileSectionKind;
+ (function (BundleFileSectionKind) {
+ BundleFileSectionKind["Prologue"] = "prologue";
+ BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
+ BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
+ BundleFileSectionKind["Reference"] = "reference";
+ BundleFileSectionKind["Type"] = "type";
+ BundleFileSectionKind["Lib"] = "lib";
+ BundleFileSectionKind["Prepend"] = "prepend";
+ BundleFileSectionKind["Text"] = "text";
+ BundleFileSectionKind["Internal"] = "internal";
+ // comments?
+ })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
var ListFormat;
(function (ListFormat) {
ListFormat[ListFormat["None"] = 0] = "None";
@@ -4026,8 +4150,11 @@
*/
/* @internal */
function generateDjb2Hash(data) {
- var chars = data.split("").map(function (str) { return str.charCodeAt(0); });
- return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381);
+ var acc = 5381;
+ for (var i = 0; i < data.length; i++) {
+ acc = ((acc << 5) + acc) + data.charCodeAt(i);
+ }
+ return acc.toString();
}
ts.generateDjb2Hash = generateDjb2Hash;
/**
@@ -4287,6 +4414,8 @@
: FileWatcherEventKind.Changed;
}
ts.getFileWatcherEventKind = getFileWatcherEventKind;
+ /*@internal*/
+ ts.ignoredPaths = ["/node_modules/.", "/.git"];
/**
* 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
@@ -4311,6 +4440,8 @@
else {
directoryWatcher = {
watcher: host.watchDirectory(dirName, function (fileName) {
+ if (isIgnoredPath(fileName))
+ return;
// Call the actual callback
callbackCache.forEach(function (callbacks, rootDirName) {
if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
@@ -4360,7 +4491,7 @@
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 filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
+ return !isIgnoredPath(childFullName) && 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;
/**
@@ -4377,6 +4508,16 @@
(newChildWatches || (newChildWatches = [])).push(childWatcher);
}
}
+ function isIgnoredPath(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
+ }
+ function isInPath(path, searchPath) {
+ if (ts.stringContains(path, searchPath))
+ return true;
+ if (host.useCaseSensitiveFileNames)
+ return false;
+ return ts.stringContains(toCanonicalFilePath(path), searchPath);
+ }
}
ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher;
function getNodeMajorVersion() {
@@ -4445,8 +4586,18 @@
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!nodeSystem.directoryExists(directoryName)) {
+ // Wrapped in a try-catch to prevent crashing if we are in a race
+ // with another copy of ourselves to create the same directory
+ try {
_fs.mkdirSync(directoryName);
}
+ catch (e) {
+ if (e.code !== "EEXIST") {
+ // Failed for some other reason (access denied?); still throw
+ throw e;
+ }
+ }
+ }
},
getExecutingFilePath: function () {
return __filename;
@@ -4462,7 +4613,7 @@
getModifiedTime: getModifiedTime,
setModifiedTime: setModifiedTime,
deleteFile: deleteFile,
- createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash,
+ createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
createSHA256Hash: _crypto ? createSHA256Hash : undefined,
getMemoryUsage: function () {
if (global.gc) {
@@ -4850,7 +5001,7 @@
}
}
function readDirectory(path, extensions, excludes, includes, depth) {
- return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries);
+ return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
}
function fileSystemEntryExists(path, entryKind) {
try {
@@ -4906,11 +5057,6 @@
return;
}
}
- function createMD5HashUsingNativeCrypto(data) {
- var hash = _crypto.createHash("md5");
- hash.update(data);
- return hash.digest("hex");
- }
function createSHA256Hash(data) {
var hash = _crypto.createHash("sha256");
hash.update(data);
@@ -5171,7 +5317,6 @@
Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."),
Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."),
- Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."),
Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."),
A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."),
Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."),
@@ -5262,6 +5407,8 @@
An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."),
A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."),
A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."),
+ readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types: diag(1354, ts.DiagnosticCategory.Error, "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354", "'readonly' type modifier is only permitted on array and tuple literal types."),
+ A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal: diag(1355, ts.DiagnosticCategory.Error, "A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal_1355", "A 'const' assertion can only be applied to a string, number, boolean, array, or object literal."),
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."),
@@ -5356,7 +5503,7 @@
Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."),
Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
- Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."),
+ This_overload_signature_is_not_compatible_with_its_implementation_signature: diag(2394, ts.DiagnosticCategory.Error, "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394", "This overload signature is not compatible with its implementation signature."),
Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."),
Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."),
Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."),
@@ -5529,15 +5676,20 @@
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."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."),
Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."),
_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
+ Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."),
+ Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
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."),
@@ -5644,6 +5796,12 @@
This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."),
This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."),
_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."),
+ Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided: diag(2748, ts.DiagnosticCategory.Error, "Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided_2748", "Cannot access ambient const enums when the '--isolatedModules' flag is provided."),
+ _0_refers_to_a_value_but_is_being_used_as_a_type_here: diag(2749, ts.DiagnosticCategory.Error, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_2749", "'{0}' refers to a value, but is being used as a type here."),
+ The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
+ Circularity_originates_in_type_at_this_location: diag(2751, ts.DiagnosticCategory.Error, "Circularity_originates_in_type_at_this_location_2751", "Circularity originates in type at this location."),
+ The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
+ Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
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}'."),
@@ -5727,6 +5885,7 @@
Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
@@ -5775,7 +5934,7 @@
Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."),
Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
- Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."),
+ Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'."),
Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."),
Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
@@ -5994,6 +6153,16 @@
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."),
Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
+ Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
+ Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
+ A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
+ A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
+ Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
+ Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
+ Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
+ Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
+ Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
+ Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
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."),
The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
@@ -6030,7 +6199,7 @@
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'."),
+ The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."),
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."),
Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
@@ -6210,6 +6379,7 @@
Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
+ Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
};
})(ts || (ts = {}));
var ts;
@@ -6697,16 +6867,20 @@
return pos;
}
var shebangTriviaRegex = /^#!.*/;
+ /*@internal*/
function isShebangTrivia(text, pos) {
// Shebangs check must only be done at the start of the file
ts.Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
+ ts.isShebangTrivia = isShebangTrivia;
+ /*@internal*/
function scanShebangTrivia(text, pos) {
var shebang = shebangTriviaRegex.exec(text)[0];
pos = pos + shebang.length;
return pos;
}
+ ts.scanShebangTrivia = scanShebangTrivia;
/**
* Invokes a callback for each comment range following the provided position.
*
@@ -6733,8 +6907,15 @@
var pendingKind;
var pendingHasTrailingNewLine;
var hasPendingCommentRange = false;
- var collecting = trailing || pos === 0;
+ var collecting = trailing;
var accumulator = initial;
+ if (pos === 0) {
+ collecting = true;
+ var shebang = getShebang(text);
+ if (shebang) {
+ pos = shebang.length;
+ }
+ }
scan: while (pos >= 0 && pos < text.length) {
var ch = text.charCodeAt(pos);
switch (ch) {
@@ -7969,6 +8150,7 @@
}
pos++;
}
+ tokenValue = text.substring(startPos, pos);
return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
}
// Scans a JSX identifier; these differ from normal identifiers in that
@@ -8050,8 +8232,8 @@
pos++;
return token = 14 /* NoSubstitutionTemplateLiteral */;
}
- if (isIdentifierStart(ch, 6 /* Latest */)) {
- while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) {
+ if (isIdentifierStart(ch, 7 /* Latest */)) {
+ while (isIdentifierPart(text.charCodeAt(pos), 7 /* Latest */) && pos < end) {
pos++;
}
tokenValue = text.substring(tokenPos, pos);
@@ -8409,7 +8591,7 @@
}
}
function getSourceFileOfNode(node) {
- while (node && node.kind !== 279 /* SourceFile */) {
+ while (node && node.kind !== 284 /* SourceFile */) {
node = node.parent;
}
return node;
@@ -8496,10 +8678,7 @@
return !nodeIsMissing(node);
}
ts.nodeIsPresent = nodeIsPresent;
- /**
- * Prepends statements to an array while taking care of prologue directives.
- */
- function addStatementsAfterPrologue(to, from) {
+ function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
if (from === undefined || from.length === 0)
return to;
var statementIndex = 0;
@@ -8512,7 +8691,44 @@
to.splice.apply(to, [statementIndex, 0].concat(from));
return to;
}
- ts.addStatementsAfterPrologue = addStatementsAfterPrologue;
+ function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
+ if (statement === undefined)
+ return to;
+ 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(statementIndex, 0, statement);
+ return to;
+ }
+ function isAnyPrologueDirective(node) {
+ return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
+ }
+ /**
+ * Prepends statements to an array while taking care of prologue directives.
+ */
+ function insertStatementsAfterStandardPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isPrologueDirective);
+ }
+ ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
+ function insertStatementsAfterCustomPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
+ }
+ ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
+ /**
+ * Prepends statements to an array while taking care of prologue directives.
+ */
+ function insertStatementAfterStandardPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isPrologueDirective);
+ }
+ ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
+ function insertStatementAfterCustomPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
+ }
+ ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
/**
* Determine if the given comment is a triple-slash
*
@@ -8555,7 +8771,7 @@
// 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 === 306 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 311 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -8574,7 +8790,7 @@
}
ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
function isJSDocTypeExpressionOrChild(node) {
- return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
+ return node.kind === 288 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
}
function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
@@ -8701,7 +8917,7 @@
return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body);
}
function isBlockScopedContainerTopLevel(node) {
- return node.kind === 279 /* SourceFile */ ||
+ return node.kind === 284 /* SourceFile */ ||
node.kind === 244 /* ModuleDeclaration */ ||
ts.isFunctionLike(node);
}
@@ -8719,7 +8935,7 @@
// - 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 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node.parent);
case 245 /* ModuleBlock */:
return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
@@ -8737,7 +8953,7 @@
ts.isEffectiveExternalModule = isEffectiveExternalModule;
function isBlockScope(node, parentNode) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 274 /* CatchClause */:
case 244 /* ModuleDeclaration */:
@@ -8762,9 +8978,9 @@
ts.isBlockScope = isBlockScope;
function isDeclarationWithTypeParameters(node) {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
- case 293 /* JSDocSignature */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 298 /* JSDocSignature */:
return true;
default:
ts.assertType(node);
@@ -8780,12 +8996,12 @@
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
@@ -8930,7 +9146,7 @@
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* 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
@@ -9105,7 +9321,7 @@
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case 150 /* TypeParameter */:
return node === parent.constraint;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return node === parent.constraint;
case 154 /* PropertyDeclaration */:
case 153 /* PropertySignature */:
@@ -9365,7 +9581,7 @@
}
ts.getContainingClass = getContainingClass;
function getThisContainer(node, includeArrowFunctions) {
- ts.Debug.assert(node.kind !== 279 /* SourceFile */);
+ ts.Debug.assert(node.kind !== 284 /* SourceFile */);
while (true) {
node = node.parent;
if (!node) {
@@ -9419,7 +9635,7 @@
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 243 /* EnumDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return node;
}
}
@@ -9502,6 +9718,11 @@
}
}
ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
+ function isSuperOrSuperProperty(node) {
+ return node.kind === 98 /* SuperKeyword */
+ || isSuperProperty(node);
+ }
+ ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
/**
* Determines whether a node is a property or element access expression for `super`.
*/
@@ -10127,7 +10348,7 @@
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
function isJSDocTypeAlias(node) {
- return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 309 /* JSDocTypedefTag */ || node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocTypeAlias = isJSDocTypeAlias;
function isTypeAlias(node) {
@@ -10271,7 +10492,7 @@
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 === 290 /* JSDocVariadicType */;
+ return node.dotDotDotToken !== undefined || !!type && type.kind === 295 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -10509,14 +10730,15 @@
}
ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
function getEffectiveBaseTypeNode(node) {
- if (isInJSFile(node)) {
+ var baseType = getClassExtendsHeritageElement(node);
+ if (baseType && isInJSFile(node)) {
// Prefer an @augments tag because it may have type parameters.
var tag = ts.getJSDocAugmentsTag(node);
if (tag) {
return tag.class;
}
}
- return getClassExtendsHeritageElement(node);
+ return baseType;
}
ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
function getClassExtendsHeritageElement(node) {
@@ -10755,7 +10977,7 @@
|| kind === 158 /* GetAccessor */
|| kind === 159 /* SetAccessor */
|| kind === 244 /* ModuleDeclaration */
- || kind === 279 /* SourceFile */;
+ || kind === 284 /* SourceFile */;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(range) {
@@ -10832,7 +11054,7 @@
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return 0;
case 208 /* SpreadElement */:
return 1;
@@ -11150,6 +11372,9 @@
lineStart = true;
}
}
+ function getTextPosWithWriteLine() {
+ return lineStart ? output.length : (output.length + newLine.length);
+ }
reset();
return {
write: write,
@@ -11178,7 +11403,8 @@
writeStringLiteral: write,
writeSymbol: function (s, _) { return write(s); },
writeTrailingSemicolon: write,
- writeComment: write
+ writeComment: write,
+ getTextPosWithWriteLine: getTextPosWithWriteLine
};
}
ts.createTextWriter = createTextWriter;
@@ -11307,23 +11533,27 @@
function getSourceFilesToEmit(host, targetSourceFile) {
var options = host.getCompilerOptions();
var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); };
+ var getResolvedProjectReferenceToRedirect = function (fileName) { return host.getResolvedProjectReferenceToRedirect(fileName); };
if (options.outFile || options.out) {
var moduleKind = ts.getEmitModuleKind(options);
var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
// Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
return ts.filter(host.getSourceFiles(), function (sourceFile) {
- return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary);
+ return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect);
});
}
else {
var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
- return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); });
+ return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
}
}
ts.getSourceFilesToEmit = getSourceFilesToEmit;
/** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
- function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) {
- return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile);
+ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect) {
+ return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
+ !sourceFile.isDeclarationFile &&
+ !isSourceFileFromExternalLibrary(sourceFile) &&
+ !(isJsonSourceFile(sourceFile) && getResolvedProjectReferenceToRedirect(sourceFile.fileName));
}
ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
function getSourceFilePathInNewDir(fileName, host, newDirPath) {
@@ -11469,7 +11699,7 @@
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 === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 296 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
}
/**
* Gets the effective type annotation of the value parameter of a set accessor. If the node
@@ -12374,7 +12604,7 @@
}
ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
function getObjectFlags(type) {
- return type.flags & 524288 /* Object */ ? type.objectFlags : 0;
+ return type.flags & 3899392 /* ObjectFlagsType */ ? type.objectFlags : 0;
}
ts.getObjectFlags = getObjectFlags;
function typeHasCallOrConstructSignatures(type, checker) {
@@ -12441,25 +12671,37 @@
|| kind === 96 /* NullKeyword */
|| kind === 132 /* NeverKeyword */
|| kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
+ || kind === 289 /* JSDocAllType */
+ || kind === 290 /* JSDocUnknownType */
+ || kind === 291 /* JSDocNullableType */
+ || kind === 292 /* JSDocNonNullableType */
+ || kind === 293 /* JSDocOptionalType */
+ || kind === 294 /* JSDocFunctionType */
+ || kind === 295 /* JSDocVariadicType */;
}
ts.isTypeNodeKind = isTypeNodeKind;
function isAccessExpression(node) {
return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */;
}
ts.isAccessExpression = isAccessExpression;
+ function isBundleFileTextLike(section) {
+ switch (section.kind) {
+ case "text" /* Text */:
+ case "internal" /* Internal */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isBundleFileTextLike = isBundleFileTextLike;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
switch (options.target) {
- case 6 /* ESNext */:
+ case 7 /* ESNext */:
return "lib.esnext.full.d.ts";
+ case 6 /* ES2019 */:
+ return "lib.es2019.full.d.ts";
case 5 /* ES2018 */:
return "lib.es2018.full.d.ts";
case 4 /* ES2017 */:
@@ -12913,8 +13155,8 @@
switch (declaration.kind) {
case 72 /* Identifier */:
return declaration;
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */: {
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */: {
var name = declaration.name;
if (name.kind === 148 /* QualifiedName */) {
return name.right;
@@ -12938,7 +13180,7 @@
return undefined;
}
}
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
case 254 /* ExportAssignment */: {
var expression = declaration.expression;
@@ -13142,7 +13384,7 @@
return ts.emptyArray;
}
if (ts.isJSDocTypeAlias(node)) {
- ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */);
+ ts.Debug.assert(node.parent.kind === 296 /* JSDocComment */);
return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
}
if (node.typeParameters) {
@@ -13404,12 +13646,17 @@
return node.kind === 194 /* TypeAssertionExpression */;
}
ts.isTypeAssertion = isTypeAssertion;
+ function isConstTypeReference(node) {
+ return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
+ node.typeName.escapedText === "const" && !node.typeArguments;
+ }
+ ts.isConstTypeReference = isConstTypeReference;
function isParenthesizedExpression(node) {
return node.kind === 195 /* ParenthesizedExpression */;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 308 /* PartiallyEmittedExpression */) {
+ while (node.kind === 313 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13756,108 +14003,128 @@
ts.isEnumMember = isEnumMember;
// Top-level nodes
function isSourceFile(node) {
- return node.kind === 279 /* SourceFile */;
+ return node.kind === 284 /* SourceFile */;
}
ts.isSourceFile = isSourceFile;
function isBundle(node) {
- return node.kind === 280 /* Bundle */;
+ return node.kind === 285 /* Bundle */;
}
ts.isBundle = isBundle;
function isUnparsedSource(node) {
- return node.kind === 281 /* UnparsedSource */;
+ return node.kind === 286 /* UnparsedSource */;
}
ts.isUnparsedSource = isUnparsedSource;
+ function isUnparsedPrepend(node) {
+ return node.kind === 280 /* UnparsedPrepend */;
+ }
+ ts.isUnparsedPrepend = isUnparsedPrepend;
+ function isUnparsedTextLike(node) {
+ switch (node.kind) {
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isUnparsedTextLike = isUnparsedTextLike;
+ function isUnparsedNode(node) {
+ return isUnparsedTextLike(node) ||
+ node.kind === 279 /* UnparsedPrologue */ ||
+ node.kind === 283 /* UnparsedSyntheticReference */;
+ }
+ ts.isUnparsedNode = isUnparsedNode;
// JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 283 /* JSDocTypeExpression */;
+ return node.kind === 288 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 284 /* JSDocAllType */;
+ return node.kind === 289 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 285 /* JSDocUnknownType */;
+ return node.kind === 290 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 286 /* JSDocNullableType */;
+ return node.kind === 291 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 287 /* JSDocNonNullableType */;
+ return node.kind === 292 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 288 /* JSDocOptionalType */;
+ return node.kind === 293 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 289 /* JSDocFunctionType */;
+ return node.kind === 294 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 290 /* JSDocVariadicType */;
+ return node.kind === 295 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 291 /* JSDocComment */;
+ return node.kind === 296 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 295 /* JSDocAugmentsTag */;
+ return node.kind === 300 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 296 /* JSDocClassTag */;
+ return node.kind === 301 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocEnumTag(node) {
- return node.kind === 298 /* JSDocEnumTag */;
+ return node.kind === 303 /* JSDocEnumTag */;
}
ts.isJSDocEnumTag = isJSDocEnumTag;
function isJSDocThisTag(node) {
- return node.kind === 301 /* JSDocThisTag */;
+ return node.kind === 306 /* JSDocThisTag */;
}
ts.isJSDocThisTag = isJSDocThisTag;
function isJSDocParameterTag(node) {
- return node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 300 /* JSDocReturnTag */;
+ return node.kind === 305 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 302 /* JSDocTypeTag */;
+ return node.kind === 307 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 303 /* JSDocTemplateTag */;
+ return node.kind === 308 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 304 /* JSDocTypedefTag */;
+ return node.kind === 309 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */;
+ return node.kind === 310 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 310 /* JSDocPropertyTag */ || node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 292 /* JSDocTypeLiteral */;
+ return node.kind === 297 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
function isJSDocCallbackTag(node) {
- return node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocCallbackTag = isJSDocCallbackTag;
function isJSDocSignature(node) {
- return node.kind === 293 /* JSDocSignature */;
+ return node.kind === 298 /* JSDocSignature */;
}
ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
@@ -13868,7 +14135,7 @@
(function (ts) {
/* @internal */
function isSyntaxList(n) {
- return n.kind === 306 /* SyntaxList */;
+ return n.kind === 311 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
/* @internal */
@@ -14020,11 +14287,11 @@
switch (kind) {
case 155 /* MethodSignature */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 166 /* ConstructorType */:
return true;
default:
@@ -14315,8 +14582,8 @@
case 208 /* SpreadElement */:
case 212 /* AsExpression */:
case 210 /* OmittedExpression */:
- case 309 /* CommaListExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 314 /* CommaListExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -14330,12 +14597,12 @@
ts.isAssertionExpression = isAssertionExpression;
/* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 308 /* PartiallyEmittedExpression */;
+ return node.kind === 313 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
/* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 307 /* NotEmittedStatement */;
+ return node.kind === 312 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
@@ -14446,9 +14713,9 @@
|| kind === 242 /* TypeAliasDeclaration */
|| kind === 150 /* TypeParameter */
|| kind === 237 /* VariableDeclaration */
- || kind === 304 /* JSDocTypedefTag */
- || kind === 297 /* JSDocCallbackTag */
- || kind === 305 /* JSDocPropertyTag */;
+ || kind === 309 /* JSDocTypedefTag */
+ || kind === 302 /* JSDocCallbackTag */
+ || kind === 310 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
return kind === 239 /* FunctionDeclaration */
@@ -14483,14 +14750,14 @@
|| kind === 219 /* VariableStatement */
|| kind === 224 /* WhileStatement */
|| kind === 231 /* WithStatement */
- || kind === 307 /* NotEmittedStatement */
- || kind === 311 /* EndOfDeclarationMarker */
- || kind === 310 /* MergeDeclarationMarker */;
+ || kind === 312 /* NotEmittedStatement */
+ || kind === 316 /* EndOfDeclarationMarker */
+ || kind === 315 /* MergeDeclarationMarker */;
}
/* @internal */
function isDeclaration(node) {
if (node.kind === 150 /* TypeParameter */) {
- return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node);
+ return (node.parent && node.parent.kind !== 308 /* JSDocTemplateTag */) || ts.isInJSFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -14585,18 +14852,18 @@
/** True if node is of some JSDoc syntax kind. */
/* @internal */
function isJSDocNode(node) {
- return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */;
+ return node.kind >= 288 /* FirstJSDocNode */ && node.kind <= 310 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
+ return node.kind === 296 /* 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 >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */;
+ return node.kind >= 299 /* FirstJSDocTagNode */ && node.kind <= 310 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -14913,6 +15180,10 @@
return !!(compilerOptions.declaration || compilerOptions.composite);
}
ts.getEmitDeclarations = getEmitDeclarations;
+ function isIncrementalCompilation(options) {
+ return !!(options.incremental || options.composite);
+ }
+ ts.isIncrementalCompilation = isIncrementalCompilation;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
}
@@ -15600,7 +15871,7 @@
}
ts.getRegexFromPattern = getRegexFromPattern;
/** @param path directory of the tsconfig.json */
- function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) {
+ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
path = ts.normalizePath(path);
currentDirectory = ts.normalizePath(currentDirectory);
var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
@@ -15610,12 +15881,18 @@
// Associate an array of results with each include regex. This keeps results in order of the "include" order.
// If there are no "includes", then just put everything in results[0].
var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
+ var visited = ts.createMap();
+ var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
var basePath = _a[_i];
visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
}
return ts.flatten(results);
function visitDirectory(path, absolutePath, depth) {
+ var canonicalPath = toCanonical(realpath(absolutePath));
+ if (visited.has(canonicalPath))
+ return;
+ visited.set(canonicalPath, true);
var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
var _loop_1 = function (current) {
var name = combinePaths(path, current);
@@ -15998,6 +16275,19 @@
return arr.slice(index);
}
ts.sliceAfter = sliceAfter;
+ function addRelatedInfo(diagnostic) {
+ var _a;
+ var relatedInformation = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ relatedInformation[_i - 1] = arguments[_i];
+ }
+ if (!diagnostic.relatedInformation) {
+ diagnostic.relatedInformation = [];
+ }
+ (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
+ return diagnostic;
+ }
+ ts.addRelatedInfo = addRelatedInfo;
function minAndMax(arr, getValue) {
Debug.assert(arr.length !== 0);
var min = getValue(arr[0]);
@@ -16197,7 +16487,7 @@
var SourceFileConstructor;
// tslint:enable variable-name
function createNode(kind, pos, end) {
- if (kind === 279 /* SourceFile */) {
+ if (kind === 284 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 72 /* Identifier */) {
@@ -16448,7 +16738,7 @@
case 218 /* Block */:
case 245 /* ModuleBlock */:
return visitNodes(cbNode, cbNodes, node.statements);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return visitNodes(cbNode, cbNodes, node.statements) ||
visitNode(cbNode, node.endOfFileToken);
case 219 /* VariableStatement */:
@@ -16597,7 +16887,7 @@
return visitNode(cbNode, node.expression);
case 258 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
case 260 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
@@ -16626,60 +16916,60 @@
return visitNode(cbNode, node.tagName);
case 171 /* OptionalType */:
case 172 /* RestType */:
- case 283 /* JSDocTypeExpression */:
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 288 /* JSDocOptionalType */:
- case 290 /* JSDocVariadicType */:
+ case 288 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 293 /* JSDocOptionalType */:
+ case 295 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return visitNode(cbNode, node.tagName) ||
(node.isNameFirst
? visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression)
: visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name));
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.constraint) ||
visitNodes(cbNode, cbNodes, node.typeParameters);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return visitNode(cbNode, node.tagName) ||
(node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ node.typeExpression.kind === 288 /* JSDocTypeExpression */
? visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName)
: visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression));
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.typeExpression);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return ts.forEach(node.jsDocPropertyTags, cbNode);
- case 294 /* JSDocTag */:
- case 296 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
return visitNode(cbNode, node.tagName);
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -16759,7 +17049,7 @@
(function (Parser) {
// Share a single scanner across all calls to parse a source file. This helps speed things
// up by avoiding the cost of creating/compiling scanners over and over again.
- var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true);
+ var scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ true);
var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */;
// capture constructors in 'initializeState' to avoid null checks
// tslint:disable variable-name
@@ -17053,7 +17343,7 @@
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(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
+ var sourceFile = new SourceFileConstructor(284 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
@@ -18253,9 +18543,9 @@
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(284 /* JSDocAllType */);
+ var result = createNode(289 /* JSDocAllType */);
if (postFixEquals) {
- return createPostfixType(288 /* JSDocOptionalType */, result);
+ return createPostfixType(293 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -18263,7 +18553,7 @@
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(287 /* JSDocNonNullableType */);
+ var result = createNode(292 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -18287,18 +18577,18 @@
token() === 30 /* GreaterThanToken */ ||
token() === 59 /* EqualsToken */ ||
token() === 50 /* BarToken */) {
- var result = createNode(285 /* JSDocUnknownType */, pos);
+ var result = createNode(290 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(286 /* JSDocNullableType */, pos);
+ var result = createNode(291 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(289 /* JSDocFunctionType */);
+ var result = createNodeWithJSDoc(294 /* JSDocFunctionType */);
nextToken();
fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
@@ -18322,12 +18612,12 @@
var type = parseTypeOrTypePredicate();
scanner.setInJSDocType(false);
if (dotdotdot) {
- var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos);
+ var variadic = createNode(295 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 59 /* EqualsToken */) {
- return createPostfixType(288 /* JSDocOptionalType */, type);
+ return createPostfixType(293 /* JSDocOptionalType */, type);
}
return type;
}
@@ -18699,7 +18989,7 @@
return finishNode(node);
}
var type = parseType();
- if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) {
+ if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 291 /* JSDocNullableType */ && type.pos === type.type.pos) {
type.kind = 171 /* OptionalType */;
}
return type;
@@ -18837,6 +19127,7 @@
case 135 /* NumberKeyword */:
case 146 /* BigIntKeyword */:
case 123 /* BooleanKeyword */:
+ case 133 /* ReadonlyKeyword */:
case 139 /* SymbolKeyword */:
case 142 /* UniqueKeyword */:
case 106 /* VoidKeyword */:
@@ -18885,14 +19176,14 @@
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 52 /* ExclamationToken */:
- type = createPostfixType(287 /* JSDocNonNullableType */, type);
+ type = createPostfixType(292 /* JSDocNonNullableType */, type);
break;
case 56 /* 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 = createPostfixType(286 /* JSDocNullableType */, type);
+ type = createPostfixType(291 /* JSDocNullableType */, type);
break;
case 22 /* OpenBracketToken */:
parseExpected(22 /* OpenBracketToken */);
@@ -18942,6 +19233,7 @@
switch (operator) {
case 129 /* KeyOfKeyword */:
case 142 /* UniqueKeyword */:
+ case 133 /* ReadonlyKeyword */:
return parseTypeOperator(operator);
case 127 /* InferKeyword */:
return parseInferType();
@@ -20001,7 +20293,8 @@
}
function parseJsxText() {
var node = createNode(11 /* JsxText */);
- node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
+ node.text = scanner.getTokenValue();
+ node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
currentToken = scanner.scanJsxToken();
return finishNode(node);
}
@@ -21816,8 +22109,8 @@
var JSDocParser;
(function (JSDocParser) {
function parseJSDocTypeExpressionForTests(content, start, length) {
- initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
- sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
+ initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ sourceFile = createSourceFile("file.js", 7 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
scanner.setText(content, start, length);
currentToken = scanner.scan();
var jsDocTypeExpression = parseJSDocTypeExpression();
@@ -21828,7 +22121,7 @@
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
// Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(283 /* JSDocTypeExpression */);
+ var result = createNode(288 /* JSDocTypeExpression */);
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -21839,7 +22132,7 @@
}
JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
function parseIsolatedJSDocComment(content, start, length) {
- initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion
var jsDoc = parseJSDocCommentWorker(start, length);
var diagnostics = parseDiagnostics;
@@ -21991,7 +22284,7 @@
}
}
function createJSDocComment() {
- var result = createNode(291 /* JSDocComment */, start);
+ var result = createNode(296 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -22158,7 +22451,7 @@
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(start, tagName) {
- var result = createNode(294 /* JSDocTag */, start);
+ var result = createNode(299 /* JSDocTag */, start);
result.tagName = tagName;
return finishNode(result);
}
@@ -22217,8 +22510,8 @@
typeExpression = tryParseTypeExpression();
}
var result = target === 1 /* Property */ ?
- createNode(305 /* JSDocPropertyTag */, start) :
- createNode(299 /* JSDocParameterTag */, start);
+ createNode(310 /* JSDocPropertyTag */, start) :
+ createNode(304 /* JSDocParameterTag */, start);
var comment = parseTagComments(indent + scanner.getStartPos() - start);
var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
if (nestedTypeLiteral) {
@@ -22235,18 +22528,18 @@
}
function parseNestedTypeLiteral(typeExpression, name, target, indent) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(288 /* 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, indent, name); })) {
- if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) {
+ if (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 169 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
@@ -22257,25 +22550,25 @@
}
}
function parseReturnTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 305 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(300 /* JSDocReturnTag */, start);
+ var result = createNode(305 /* JSDocReturnTag */, start);
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 307 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(302 /* JSDocTypeTag */, start);
+ var result = createNode(307 /* JSDocTypeTag */, start);
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(start, tagName) {
- var result = createNode(295 /* JSDocAugmentsTag */, start);
+ var result = createNode(300 /* JSDocAugmentsTag */, start);
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
return finishNode(result);
@@ -22302,19 +22595,19 @@
return node;
}
function parseClassTag(start, tagName) {
- var tag = createNode(296 /* JSDocClassTag */, start);
+ var tag = createNode(301 /* JSDocClassTag */, start);
tag.tagName = tagName;
return finishNode(tag);
}
function parseThisTag(start, tagName) {
- var tag = createNode(301 /* JSDocThisTag */, start);
+ var tag = createNode(306 /* JSDocThisTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
return finishNode(tag);
}
function parseEnumTag(start, tagName) {
- var tag = createNode(298 /* JSDocEnumTag */, start);
+ var tag = createNode(303 /* JSDocEnumTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
@@ -22323,7 +22616,7 @@
function parseTypedefTag(start, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespaceOrAsterisk();
- var typedefTag = createNode(304 /* JSDocTypedefTag */, start);
+ var typedefTag = createNode(309 /* JSDocTypedefTag */, start);
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace();
typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
@@ -22337,9 +22630,9 @@
var childTypeTag = void 0;
while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start);
}
- if (child.kind === 302 /* JSDocTypeTag */) {
+ if (child.kind === 307 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -22385,14 +22678,14 @@
return typeNameOrNamespaceName;
}
function parseCallbackTag(start, tagName, indent) {
- var callbackTag = createNode(297 /* JSDocCallbackTag */, start);
+ var callbackTag = createNode(302 /* JSDocCallbackTag */, start);
callbackTag.tagName = tagName;
callbackTag.fullName = parseJSDocTypeNameWithNamespace();
callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
skipWhitespace();
callbackTag.comment = parseTagComments(indent);
var child;
- var jsdocSignature = createNode(293 /* JSDocSignature */, start);
+ var jsdocSignature = createNode(298 /* JSDocSignature */, start);
jsdocSignature.parameters = [];
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
@@ -22400,7 +22693,7 @@
var returnTag = tryParse(function () {
if (parseOptionalJsdoc(58 /* AtToken */)) {
var tag = parseTag(indent);
- if (tag && tag.kind === 300 /* JSDocReturnTag */) {
+ if (tag && tag.kind === 305 /* JSDocReturnTag */) {
return tag;
}
}
@@ -22445,7 +22738,7 @@
case 58 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target, indent);
- if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) &&
+ if (child && (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) &&
target !== 4 /* CallbackParameter */ &&
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
@@ -22515,7 +22808,7 @@
skipWhitespace();
typeParameters.push(typeParameter);
} while (parseOptionalJsdoc(27 /* CommaToken */));
- var result = createNode(303 /* JSDocTemplateTag */, start);
+ var result = createNode(308 /* JSDocTemplateTag */, start);
result.tagName = tagName;
result.constraint = constraint;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -23293,6 +23586,7 @@
["es2016", "lib.es2016.d.ts"],
["es2017", "lib.es2017.d.ts"],
["es2018", "lib.es2018.d.ts"],
+ ["es2019", "lib.es2019.d.ts"],
["esnext", "lib.esnext.d.ts"],
// Host only
["dom", "lib.dom.d.ts"],
@@ -23316,12 +23610,16 @@
["es2017.string", "lib.es2017.string.d.ts"],
["es2017.intl", "lib.es2017.intl.d.ts"],
["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
+ ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
["es2018.intl", "lib.es2018.intl.d.ts"],
["es2018.promise", "lib.es2018.promise.d.ts"],
["es2018.regexp", "lib.es2018.regexp.d.ts"],
- ["esnext.array", "lib.esnext.array.d.ts"],
- ["esnext.symbol", "lib.esnext.symbol.d.ts"],
- ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"],
+ ["es2019.array", "lib.es2019.array.d.ts"],
+ ["es2019.string", "lib.es2019.string.d.ts"],
+ ["es2019.symbol", "lib.es2019.symbol.d.ts"],
+ ["esnext.array", "lib.es2019.array.d.ts"],
+ ["esnext.symbol", "lib.es2019.symbol.d.ts"],
+ ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
["esnext.intl", "lib.esnext.intl.d.ts"],
["esnext.bigint", "lib.esnext.bigint.d.ts"]
];
@@ -23467,14 +23765,15 @@
es2016: 3 /* ES2016 */,
es2017: 4 /* ES2017 */,
es2018: 5 /* ES2018 */,
- esnext: 6 /* ESNext */,
+ es2019: 6 /* ES2019 */,
+ esnext: 7 /* ESNext */,
}),
affectsSourceFile: true,
affectsModuleResolution: true,
paramType: ts.Diagnostics.VERSION,
showInSimplifiedHelpView: true,
category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT,
+ description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT,
},
{
name: "module",
@@ -23596,6 +23895,22 @@
description: ts.Diagnostics.Enable_project_compilation,
},
{
+ name: "incremental",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_incremental_compilation,
+ },
+ {
+ name: "tsBuildInfoFile",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE,
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
+ },
+ {
name: "removeComments",
type: "boolean",
showInSimplifiedHelpView: true,
@@ -25021,7 +25336,7 @@
}
function directoryOfCombinedPath(fileName, basePath) {
// Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
- // until consistient casing errors are reported
+ // until consistent casing errors are reported
return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
}
/**
@@ -27313,7 +27628,7 @@
return "__constructor" /* Constructor */;
case 165 /* FunctionType */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return "__call" /* Call */;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
@@ -27322,7 +27637,7 @@
return "__index" /* Index */;
case 255 /* ExportDeclaration */:
return "__export" /* ExportStar */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// json file should behave as
// module.exports = ...
return "export=" /* ExportEquals */;
@@ -27333,12 +27648,12 @@
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
case 151 /* 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 === 289 /* 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 === 294 /* 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;
@@ -27422,13 +27737,15 @@
message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
messageNeedsName_1 = false;
}
- if (symbol.declarations && symbol.declarations.length) {
+ var multipleDefaultExports_1 = false;
+ if (ts.length(symbol.declarations)) {
// If the current node is a default export of some sort, then check if
// there are any other default exports that we need to error on.
// 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;
+ multipleDefaultExports_1 = true;
}
else {
// This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
@@ -27439,14 +27756,22 @@
(node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) {
message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
messageNeedsName_1 = false;
+ multipleDefaultExports_1 = true;
}
}
}
- 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);
+ var declarationName_1 = ts.getNameOfDeclaration(node) || node;
+ var relatedInformation_1 = [];
+ ts.forEach(symbol.declarations, function (declaration, index) {
+ var decl = ts.getNameOfDeclaration(declaration) || declaration;
+ var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
+ file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo(diag, createDiagnosticForNode(declarationName_1, index === 0 ? ts.Diagnostics.Another_export_default_is_here : ts.Diagnostics.and_here)) : diag);
+ if (multipleDefaultExports_1) {
+ relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
+ }
+ });
+ var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
+ file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInformation_1)) : diag);
symbol = createSymbol(0 /* None */, name);
}
}
@@ -27562,7 +27887,7 @@
}
}
// We create a return control flow graph for IIFEs and constructors. For constructors
- // we use the return control flow graph in strict property intialization checks.
+ // we use the return control flow graph in strict property initialization checks.
currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined;
currentBreakTarget = undefined;
currentContinueTarget = undefined;
@@ -27577,7 +27902,7 @@
if (hasExplicitReturn)
node.flags |= 256 /* HasExplicitReturn */;
}
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
node.flags |= emitFlags;
}
if (currentReturnTarget) {
@@ -27721,12 +28046,12 @@
case 191 /* CallExpression */:
bindCallExpressionFlow(node);
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
bindJSDocTypeAlias(node);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
- case 279 /* SourceFile */: {
+ case 284 /* SourceFile */: {
bindEachFunctionsFirst(node.statements);
bind(node.endOfFileToken);
break;
@@ -28413,7 +28738,7 @@
case 243 /* EnumDeclaration */:
case 188 /* ObjectLiteralExpression */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 268 /* JsxAttributes */:
return 1 /* IsContainer */;
case 241 /* InterfaceDeclaration */:
@@ -28422,7 +28747,7 @@
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
return 1 /* IsContainer */ | 32 /* HasLocals */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
case 156 /* MethodDeclaration */:
if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
@@ -28435,8 +28760,8 @@
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
- case 289 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
case 165 /* FunctionType */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
@@ -28490,7 +28815,7 @@
// handlers to take care of declaring these child members.
case 244 /* ModuleDeclaration */:
return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return declareSourceFileMember(node, symbolFlags, symbolExcludes);
case 209 /* ClassExpression */:
case 240 /* ClassDeclaration */:
@@ -28498,7 +28823,7 @@
case 243 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 188 /* ObjectLiteralExpression */:
case 241 /* InterfaceDeclaration */:
case 268 /* JsxAttributes */:
@@ -28512,7 +28837,7 @@
case 166 /* ConstructorType */:
case 160 /* CallSignature */:
case 161 /* ConstructSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 162 /* IndexSignature */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
@@ -28522,9 +28847,9 @@
case 239 /* FunctionDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
- case 289 /* JSDocFunctionType */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 294 /* JSDocFunctionType */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
// All the children of these container types are never visible through another
@@ -28547,8 +28872,8 @@
: declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node) {
- var body = node.kind === 279 /* SourceFile */ ? node : node.body;
- if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
+ var body = node.kind === 284 /* SourceFile */ ? node : node.body;
+ if (body && (body.kind === 284 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
var stat = _a[_i];
if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) {
@@ -28682,7 +29007,7 @@
case 244 /* ModuleDeclaration */:
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalOrCommonJsModule(container)) {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
@@ -28820,7 +29145,7 @@
function checkStrictModeFunctionDeclaration(node) {
if (languageVersion < 2 /* ES2015 */) {
// Report error if function is not top level function declaration
- if (blockScopeContainer.kind !== 279 /* SourceFile */ &&
+ if (blockScopeContainer.kind !== 284 /* SourceFile */ &&
blockScopeContainer.kind !== 244 /* ModuleDeclaration */ &&
!ts.isFunctionLike(blockScopeContainer)) {
// We check first if the name is inside class declaration or class expression; if so give explicit message
@@ -29095,12 +29420,12 @@
case 159 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */);
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
case 166 /* ConstructorType */:
return bindFunctionOrConstructorType(node);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 181 /* MappedType */:
return bindAnonymousTypeWorker(node);
case 188 /* ObjectLiteralExpression */:
@@ -29159,7 +29484,7 @@
return bindExportDeclaration(node);
case 254 /* ExportAssignment */:
return bindExportAssignment(node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
updateStrictModeStatementList(node.statements);
return bindSourceFileIfExternalModule();
case 218 /* Block */:
@@ -29169,22 +29494,22 @@
// falls through
case 245 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
- case 299 /* JSDocParameterTag */:
- if (node.parent.kind === 293 /* JSDocSignature */) {
+ case 304 /* JSDocParameterTag */:
+ if (node.parent.kind === 298 /* JSDocSignature */) {
return bindParameter(node);
}
- if (node.parent.kind !== 292 /* JSDocTypeLiteral */) {
+ if (node.parent.kind !== 297 /* JSDocTypeLiteral */) {
break;
}
// falls through
- case 305 /* JSDocPropertyTag */:
+ case 310 /* JSDocPropertyTag */:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 293 /* JSDocOptionalType */ ?
4 /* Property */ | 16777216 /* Optional */ :
4 /* Property */;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
}
}
@@ -29356,9 +29681,14 @@
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 279 /* SourceFile */:
- // this.foo assignment in a source file
- // Do not bind. It would be nice to support this someday though.
+ case 284 /* SourceFile */:
+ // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
+ if (thisContainer.commonJsModuleIndicator) {
+ declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220414 /* FunctionScopedVariableExcludes */);
+ }
break;
default:
ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer));
@@ -29368,7 +29698,7 @@
if (node.expression.kind === 100 /* ThisKeyword */) {
bindThisPropertyAssignment(node);
}
- else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) {
+ else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 284 /* SourceFile */) {
if (ts.isPrototypeAccess(node.expression)) {
bindPrototypePropertyAssignment(node, node.parent);
}
@@ -29405,7 +29735,7 @@
}
function bindObjectDefinePropertyAssignment(node) {
var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
- var isToplevel = node.parent.parent.kind === 279 /* SourceFile */;
+ var isToplevel = node.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false);
bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
}
@@ -29472,8 +29802,8 @@
function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
var namespaceSymbol = lookupSymbolForPropertyAccess(name);
var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
- ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */
- : propertyAccess.parent.parent.kind === 279 /* SourceFile */;
+ ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 284 /* SourceFile */
+ : propertyAccess.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty);
bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
}
@@ -29611,7 +29941,7 @@
}
}
function bindParameter(node) {
- if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) {
+ if (node.kind === 304 /* JSDocParameterTag */ && container.kind !== 298 /* JSDocSignature */) {
return;
}
if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) {
@@ -29869,44 +30199,37 @@
ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
function computeCallExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
+ var callee = ts.skipOuterExpressions(node.expression);
var expression = node.expression;
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */
- || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) {
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) {
// If the this node contains a SpreadExpression, or is a super call, then it is an ES6
// node.
- transformFlags |= 192 /* AssertES2015 */;
- // super property or element accesses could be inside lambdas, etc, and need a captured `this`,
- // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor)
- if (expression.transformFlags & 67108864 /* ContainsSuper */) {
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 128 /* AssertES2015 */;
+ if (ts.isSuperProperty(callee)) {
+ transformFlags |= 2048 /* ContainsLexicalThis */;
}
}
if (expression.kind === 92 /* ImportKeyword */) {
- transformFlags |= 16777216 /* ContainsDynamicImport */;
- // A dynamic 'import()' call that contains a lexical 'this' will
- // require a captured 'this' when emitting down-level.
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- transformFlags |= 16384 /* ContainsCapturedLexicalThis */;
- }
+ transformFlags |= 524288 /* ContainsDynamicImport */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */;
}
function computeNewExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */) {
// If the this node contains a SpreadElementExpression then it is an ES6
// node.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */;
}
function computeBinaryExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -29914,20 +30237,20 @@
var leftKind = node.left.kind;
if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) {
// Destructuring object assignments with are ES2015 syntax
- // and possibly ESNext if they contain rest
- transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
+ // and possibly ES2018 if they contain rest
+ transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */;
}
else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) {
// Destructuring assignments are ES2015 syntax.
- transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
+ transformFlags |= 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */;
}
else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */
|| operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) {
// Exponentiation is ES2016 syntax.
- transformFlags |= 32 /* AssertES2016 */;
+ transformFlags |= 64 /* AssertES2016 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeParameter(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -29938,147 +30261,131 @@
// syntax.
if (node.questionToken
|| node.type
- || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
+ || (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
|| ts.isThisIdentifier(name)) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// If a parameter has an accessibility modifier, then it is TypeScript syntax.
if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
- transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */;
}
- // parameters with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // parameters with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a parameter has an initializer, a binding pattern or a dotDotDot token, then
// it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
- if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
- transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */;
+ if (subtreeFlags & 65536 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* ParameterExcludes */;
+ return transformFlags & ~536870912 /* ParameterExcludes */;
}
function computeParenthesizedExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
var expression = node.expression;
var expressionKind = expression.kind;
- var expressionTransformFlags = expression.transformFlags;
// 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 === 212 /* AsExpression */
|| expressionKind === 194 /* TypeAssertionExpression */) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- // If the expression of a ParenthesizedExpression is a destructuring assignment,
- // then the ParenthesizedExpression is a destructuring assignment.
- if (expressionTransformFlags & 1024 /* DestructuringAssignment */) {
- transformFlags |= 1024 /* DestructuringAssignment */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536872257 /* OuterExpressionExcludes */;
+ return transformFlags & ~536870912 /* OuterExpressionExcludes */;
}
function computeClassDeclaration(node, subtreeFlags) {
var transformFlags;
if (ts.hasModifier(node, 2 /* Ambient */)) {
// An ambient declaration is TypeScript syntax.
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
// A ClassDeclaration is ES6 syntax.
- transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// A class with a parameter property assignment, property initializer, computed property name, or decorator is
// TypeScript syntax.
// An exported declaration may be TypeScript syntax, but is handled by the visitor
// for a namespace declaration.
- if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */)
+ if ((subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */)
|| node.typeParameters) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~638121281 /* ClassExcludes */;
+ return transformFlags & ~536888320 /* ClassExcludes */;
}
function computeClassExpression(node, subtreeFlags) {
// A ClassExpression is ES6 syntax.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// A class with a parameter property assignment, property initializer, or decorator is
// TypeScript syntax.
- if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */
+ if (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */
|| node.typeParameters) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~638121281 /* ClassExcludes */;
+ return transformFlags & ~536888320 /* ClassExcludes */;
}
function computeHeritageClause(node, subtreeFlags) {
var transformFlags = subtreeFlags;
switch (node.token) {
case 86 /* ExtendsKeyword */:
// An `extends` HeritageClause is ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 109 /* ImplementsKeyword */:
// An `implements` HeritageClause is TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
break;
default:
ts.Debug.fail("Unexpected token for heritage clause");
break;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeCatchClause(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (!node.variableDeclaration) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 8 /* AssertES2019 */;
}
else if (ts.isBindingPattern(node.variableDeclaration.name)) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637797697 /* CatchClauseExcludes */;
+ return transformFlags & ~536879104 /* CatchClauseExcludes */;
}
function computeExpressionWithTypeArguments(node, subtreeFlags) {
// An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
// extends clause of a class.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// If an ExpressionWithTypeArguments contains type arguments, then it
// is TypeScript syntax.
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeConstructor(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// TypeScript-specific modifiers and overloads are TypeScript syntax
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* ConstructorExcludes */;
+ return transformFlags & ~537372672 /* ConstructorExcludes */;
}
function computeMethod(node, subtreeFlags) {
// A MethodDeclaration is ES6 syntax.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
// overloads are TypeScript syntax.
if (node.decorators
@@ -30087,21 +30394,21 @@
|| node.type
|| (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// An async method declaration is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* MethodOrAccessorExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */);
}
function computeAccessor(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -30112,25 +30419,25 @@
|| node.type
|| (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* MethodOrAccessorExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */);
}
function computePropertyDeclaration(node, subtreeFlags) {
// A PropertyDeclaration is TypeScript syntax.
- var transformFlags = subtreeFlags | 3 /* AssertTypeScript */;
+ var transformFlags = subtreeFlags | 1 /* AssertTypeScript */;
// If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor
// so that it handle the transformation.
if (node.initializer || ts.isComputedPropertyName(node.name)) {
- transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1024 /* ContainsTypeScriptClassSyntax */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~536872960 /* PropertyExcludes */);
}
function computeFunctionDeclaration(node, subtreeFlags) {
var transformFlags;
@@ -30139,42 +30446,36 @@
if (!body || (modifierFlags & 2 /* Ambient */)) {
// An ambient declaration is TypeScript syntax.
// A FunctionDeclaration without a body is an overload and is TypeScript syntax.
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
- transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */;
+ transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */;
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (modifierFlags & 2270 /* TypeScriptModifier */
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async function declaration is ES2017 syntax.
if (modifierFlags & 256 /* Async */) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If a FunctionDeclaration's subtree has marked the container as needing to capture the
- // lexical this, or the function contains parameters with initializers, then this node is
- // ES6 syntax.
- if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) {
- transformFlags |= 192 /* AssertES2015 */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a FunctionDeclaration is generator function and is the body of a
// transformed async function, then this node can be transformed to a
// down-level generator.
- // Currently we do not support transforming any other generator fucntions
+ // Currently we do not support transforming any other generator functions
// down level.
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653620545 /* FunctionExcludes */;
+ return transformFlags & ~537373696 /* FunctionExcludes */;
}
function computeFunctionExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -30183,181 +30484,161 @@
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async function expression is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
- // function expressions with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If a FunctionExpression's subtree has marked the container as needing to capture the
- // lexical this, or the function contains parameters with initializers, then this node is
- // ES6 syntax.
- if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) {
- transformFlags |= 192 /* AssertES2015 */;
+ // function expressions with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a FunctionExpression is generator function and is the body of a
// transformed async function, then this node can be transformed to a
// down-level generator.
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653620545 /* FunctionExcludes */;
+ return transformFlags & ~537373696 /* FunctionExcludes */;
}
function computeArrowFunction(node, subtreeFlags) {
// An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async arrow function is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= 16 /* AssertES2017 */;
+ transformFlags |= 32 /* AssertES2017 */;
}
- // arrow functions with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If an ArrowFunction contains a lexical this, its container must capture the lexical this.
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- transformFlags |= 16384 /* ContainsCapturedLexicalThis */;
+ // arrow functions with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653604161 /* ArrowFunctionExcludes */;
+ return transformFlags & ~537371648 /* ArrowFunctionExcludes */;
}
function computePropertyAccess(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// If a PropertyAccessExpression starts with a super keyword, then it is
// ES6 syntax, and requires a lexical `this` binding.
- if (transformFlags & 33554432 /* Super */) {
- transformFlags ^= 33554432 /* Super */;
+ if (node.expression.kind === 98 /* SuperKeyword */) {
// super inside of an async function requires hoisting the super access (ES2017).
- // same for super inside of an async generator, which is ESNext.
- transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */;
+ // same for super inside of an async generator, which is ES2018.
+ transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~570426689 /* PropertyAccessExcludes */;
+ return transformFlags & ~536870912 /* PropertyAccessExcludes */;
}
function computeElementAccess(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- var expression = node.expression;
- var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing
// If an ElementAccessExpression starts with a super keyword, then it is
// ES6 syntax, and requires a lexical `this` binding.
- if (expressionFlags & 33554432 /* Super */) {
- transformFlags &= ~33554432 /* Super */;
+ if (node.expression.kind === 98 /* SuperKeyword */) {
// super inside of an async function requires hoisting the super access (ES2017).
- // same for super inside of an async generator, which is ESNext.
- transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */;
+ // same for super inside of an async generator, which is ES2018.
+ transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~570426689 /* PropertyAccessExcludes */;
+ return transformFlags & ~536870912 /* PropertyAccessExcludes */;
}
function computeVariableDeclaration(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- // A VariableDeclaration containing ObjectRest is ESNext syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally?
+ // A VariableDeclaration containing ObjectRest is ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// Type annotations are TypeScript syntax.
if (node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeVariableStatement(node, subtreeFlags) {
var transformFlags;
var declarationListTransformFlags = node.declarationList.transformFlags;
// An ambient declaration is TypeScript syntax.
if (ts.hasModifier(node, 2 /* Ambient */)) {
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
transformFlags = subtreeFlags;
- if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) {
- transformFlags |= 192 /* AssertES2015 */;
+ if (declarationListTransformFlags & 65536 /* ContainsBindingPattern */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeLabeledStatement(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
- if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */
+ if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */
&& ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeImportEquals(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// An ImportEqualsDeclaration with a namespace reference is TypeScript.
if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeExpressionStatement(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- // If the expression of an expression statement is a destructuring assignment,
- // then we treat the statement as ES6 so that we can indicate that we do not
- // need to hold on to the right-hand side.
- if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) {
- transformFlags |= 192 /* AssertES2015 */;
- }
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeModuleDeclaration(node, subtreeFlags) {
- var transformFlags = 3 /* AssertTypeScript */;
+ var transformFlags = 1 /* AssertTypeScript */;
var modifierFlags = ts.getModifierFlags(node);
if ((modifierFlags & 2 /* Ambient */) === 0) {
transformFlags |= subtreeFlags;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~647001409 /* ModuleExcludes */;
+ return transformFlags & ~537168896 /* ModuleExcludes */;
}
function computeVariableDeclarationList(node, subtreeFlags) {
- var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */;
- if (subtreeFlags & 2097152 /* ContainsBindingPattern */) {
- transformFlags |= 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */;
+ if (subtreeFlags & 65536 /* ContainsBindingPattern */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
// If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
if (node.flags & 3 /* BlockScoped */) {
- transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */;
+ transformFlags |= 128 /* AssertES2015 */ | 32768 /* ContainsBlockScopedBinding */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~639894849 /* VariableDeclarationListExcludes */;
+ return transformFlags & ~536944640 /* VariableDeclarationListExcludes */;
}
function computeOther(node, kind, subtreeFlags) {
// Mark transformations needed for each node
var transformFlags = subtreeFlags;
- var excludeFlags = 637535553 /* NodeExcludes */;
+ var excludeFlags = 536870912 /* NodeExcludes */;
switch (kind) {
case 121 /* AsyncKeyword */:
case 201 /* AwaitExpression */:
- // async/await is ES2017 syntax, but may be ESNext syntax (for async generators)
- transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */;
+ // async/await is ES2017 syntax, but may be ES2018 syntax (for async generators)
+ transformFlags |= 16 /* AssertES2018 */ | 32 /* AssertES2017 */;
break;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
// These nodes are TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
- excludeFlags = 536872257 /* OuterExpressionExcludes */;
+ transformFlags |= 1 /* AssertTypeScript */;
+ excludeFlags = 536870912 /* OuterExpressionExcludes */;
break;
case 115 /* PublicKeyword */:
case 113 /* PrivateKeyword */:
@@ -30370,7 +30651,7 @@
case 213 /* NonNullExpression */:
case 133 /* ReadonlyKeyword */:
// These nodes are TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
break;
case 260 /* JsxElement */:
case 261 /* JsxSelfClosingElement */:
@@ -30385,7 +30666,7 @@
case 269 /* JsxSpreadAttribute */:
case 270 /* JsxExpression */:
// These nodes are Jsx syntax.
- transformFlags |= 4 /* AssertJsx */;
+ transformFlags |= 2 /* AssertJsx */;
break;
case 14 /* NoSubstitutionTemplateLiteral */:
case 15 /* TemplateHead */:
@@ -30397,32 +30678,32 @@
case 116 /* StaticKeyword */:
case 214 /* MetaProperty */:
// These nodes are ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 10 /* StringLiteral */:
if (node.hasExtendedUnicodeEscape) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
case 8 /* NumericLiteral */:
if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
case 9 /* BigIntLiteral */:
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 4 /* AssertESNext */;
break;
case 227 /* ForOfStatement */:
// This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
if (node.awaitModifier) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 16 /* AssertES2018 */;
}
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 207 /* YieldExpression */:
// This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
// generator).
- transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */;
+ transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 131072 /* ContainsYield */;
break;
case 120 /* AnyKeyword */:
case 135 /* NumberKeyword */:
@@ -30463,115 +30744,93 @@
case 182 /* LiteralType */:
case 247 /* NamespaceExportDeclaration */:
// Types and signatures are TypeScript syntax, and exclude all other facts.
- transformFlags = 3 /* AssertTypeScript */;
- excludeFlags = -3 /* TypeExcludes */;
+ transformFlags = 1 /* AssertTypeScript */;
+ excludeFlags = -2 /* TypeExcludes */;
break;
case 149 /* ComputedPropertyName */:
// Even though computed property names are ES6, we don't treat them as such.
// This is so that they can flow through PropertyName transforms unaffected.
// Instead, we mark the container as ES6, so that it can properly handle the transform.
- transformFlags |= 524288 /* ContainsComputedPropertyName */;
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- // A computed method name like `[this.getName()](x: string) { ... }` needs to
- // distinguish itself from the normal case of a method body containing `this`:
- // `this` inside a method doesn't need to be rewritten (the method provides `this`),
- // whereas `this` inside a computed name *might* need to be rewritten if the class/object
- // is inside an arrow function:
- // `_this = this; () => class K { [_this.getName()]() { ... } }`
- // To make this distinction, use ContainsLexicalThisInComputedPropertyName
- // instead of ContainsLexicalThis for computed property names
- transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */;
- }
+ transformFlags |= 16384 /* ContainsComputedPropertyName */;
break;
case 208 /* SpreadElement */:
- transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */;
+ transformFlags |= 128 /* AssertES2015 */ | 4096 /* ContainsRestOrSpread */;
break;
case 277 /* SpreadAssignment */:
- transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */;
+ transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */;
break;
case 98 /* SuperKeyword */:
// This node is ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */;
- excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super`
+ transformFlags |= 128 /* AssertES2015 */;
+ excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super`
break;
case 100 /* ThisKeyword */:
// Mark this node and its ancestors as containing a lexical `this` keyword.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 2048 /* ContainsLexicalThis */;
break;
case 184 /* ObjectBindingPattern */:
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */;
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */;
}
- excludeFlags = 637666625 /* BindingPatternExcludes */;
+ excludeFlags = 536875008 /* BindingPatternExcludes */;
break;
case 185 /* ArrayBindingPattern */:
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- excludeFlags = 637666625 /* BindingPatternExcludes */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */;
+ excludeFlags = 536875008 /* BindingPatternExcludes */;
break;
case 186 /* BindingElement */:
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
if (node.dotDotDotToken) {
- transformFlags |= 131072 /* ContainsRestOrSpread */;
+ transformFlags |= 4096 /* ContainsRestOrSpread */;
}
break;
case 152 /* Decorator */:
// This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */;
break;
case 188 /* ObjectLiteralExpression */:
- excludeFlags = 638358849 /* ObjectLiteralExcludes */;
- if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) {
+ excludeFlags = 536896512 /* ObjectLiteralExcludes */;
+ if (subtreeFlags & 16384 /* ContainsComputedPropertyName */) {
// If an ObjectLiteralExpression contains a ComputedPropertyName, then it
// is an ES6 node.
- transformFlags |= 192 /* AssertES2015 */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 128 /* AssertES2015 */;
}
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
// If an ObjectLiteralExpression contains a spread element, then it
- // is an ES next node.
- transformFlags |= 8 /* AssertESNext */;
+ // is an ES2018 node.
+ transformFlags |= 16 /* AssertES2018 */;
}
break;
case 187 /* ArrayLiteralExpression */:
- case 192 /* NewExpression */:
- excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */;
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
- // If the this node contains a SpreadExpression, then it is an ES6
- // node.
- transformFlags |= 192 /* AssertES2015 */;
- }
+ excludeFlags = 536875008 /* ArrayLiteralOrCallOrNewExcludes */;
break;
case 223 /* DoStatement */:
case 224 /* WhileStatement */:
case 225 /* ForStatement */:
case 226 /* ForInStatement */:
// A loop containing a block scoped binding *may* need to be transformed from ES6.
- if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) {
- transformFlags |= 192 /* AssertES2015 */;
+ if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
- case 279 /* SourceFile */:
- if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) {
- transformFlags |= 192 /* AssertES2015 */;
- }
+ case 284 /* SourceFile */:
break;
case 230 /* ReturnStatement */:
- // Return statements may require an `await` in ESNext.
- transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */;
+ // Return statements may require an `await` in ES2018.
+ transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */ | 16 /* AssertES2018 */;
break;
case 228 /* ContinueStatement */:
case 229 /* BreakStatement */:
- transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */;
+ transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */;
break;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
return transformFlags & ~excludeFlags;
}
+ function propagatePropertyNameFlags(node, transformFlags) {
+ return transformFlags | (node.transformFlags & 2048 /* PropertyNamePropagatingFlags */);
+ }
/**
* Gets the transform flags to exclude when unioning the transform flags of a subtree.
*
@@ -30581,33 +30840,33 @@
*/
function getTransformFlagsSubtreeExclusions(kind) {
if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) {
- return -3 /* TypeExcludes */;
+ return -2 /* TypeExcludes */;
}
switch (kind) {
case 191 /* CallExpression */:
case 192 /* NewExpression */:
case 187 /* ArrayLiteralExpression */:
- return 637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return 536875008 /* ArrayLiteralOrCallOrNewExcludes */;
case 244 /* ModuleDeclaration */:
- return 647001409 /* ModuleExcludes */;
+ return 537168896 /* ModuleExcludes */;
case 151 /* Parameter */:
- return 637535553 /* ParameterExcludes */;
+ return 536870912 /* ParameterExcludes */;
case 197 /* ArrowFunction */:
- return 653604161 /* ArrowFunctionExcludes */;
+ return 537371648 /* ArrowFunctionExcludes */;
case 196 /* FunctionExpression */:
case 239 /* FunctionDeclaration */:
- return 653620545 /* FunctionExcludes */;
+ return 537373696 /* FunctionExcludes */;
case 238 /* VariableDeclarationList */:
- return 639894849 /* VariableDeclarationListExcludes */;
+ return 536944640 /* VariableDeclarationListExcludes */;
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
- return 638121281 /* ClassExcludes */;
+ return 536888320 /* ClassExcludes */;
case 157 /* Constructor */:
- return 653616449 /* ConstructorExcludes */;
+ return 537372672 /* ConstructorExcludes */;
case 156 /* MethodDeclaration */:
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
- return 653616449 /* MethodOrAccessorExcludes */;
+ return 537372672 /* MethodOrAccessorExcludes */;
case 120 /* AnyKeyword */:
case 135 /* NumberKeyword */:
case 146 /* BigIntKeyword */:
@@ -30625,25 +30884,25 @@
case 162 /* IndexSignature */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- return -3 /* TypeExcludes */;
+ return -2 /* TypeExcludes */;
case 188 /* ObjectLiteralExpression */:
- return 638358849 /* ObjectLiteralExcludes */;
+ return 536896512 /* ObjectLiteralExcludes */;
case 274 /* CatchClause */:
- return 637797697 /* CatchClauseExcludes */;
+ return 536879104 /* CatchClauseExcludes */;
case 184 /* ObjectBindingPattern */:
case 185 /* ArrayBindingPattern */:
- return 637666625 /* BindingPatternExcludes */;
+ return 536875008 /* BindingPatternExcludes */;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
case 195 /* ParenthesizedExpression */:
case 98 /* SuperKeyword */:
- return 536872257 /* OuterExpressionExcludes */;
+ return 536870912 /* OuterExpressionExcludes */;
case 189 /* PropertyAccessExpression */:
case 190 /* ElementAccessExpression */:
- return 570426689 /* PropertyAccessExcludes */;
+ return 536870912 /* PropertyAccessExcludes */;
default:
- return 637535553 /* NodeExcludes */;
+ return 536870912 /* NodeExcludes */;
}
}
ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
@@ -30892,6 +31151,7 @@
var enumCount = 0;
var instantiationDepth = 0;
var constraintDepth = 0;
+ var currentNode;
var emptySymbols = ts.createSymbolTable();
var identityMapper = ts.identity;
var compilerOptions = host.getCompilerOptions();
@@ -30908,8 +31168,14 @@
var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
var emitResolver = createResolver();
var nodeBuilder = createNodeBuilder();
+ var globals = ts.createSymbolTable();
var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
undefinedSymbol.declarations = [];
+ var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
+ globalThisSymbol.exports = globals;
+ globalThisSymbol.valueDeclaration = ts.createNode(72 /* Identifier */);
+ globalThisSymbol.valueDeclaration.escapedText = "globalThis";
+ globals.set(globalThisSymbol.escapedName, globalThisSymbol);
var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
var requireSymbol = createSymbol(4 /* Property */, "require");
/** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
@@ -31039,11 +31305,13 @@
isContextSensitive: isContextSensitive,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 0 /* Normal */);
},
getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */);
},
+ getExpandedParameters: getExpandedParameters,
+ hasEffectiveRestParameter: hasEffectiveRestParameter,
getConstantValue: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
return node ? getConstantValue(node) : undefined;
@@ -31105,6 +31373,8 @@
getNeverType: function () { return neverType; },
isSymbolAccessible: isSymbolAccessible,
getObjectFlags: ts.getObjectFlags,
+ isArrayType: isArrayType,
+ isTupleType: isTupleType,
isArrayLikeType: isArrayLikeType,
isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
@@ -31120,9 +31390,9 @@
getAccessibleSymbolChain: getAccessibleSymbolChain,
getTypePredicateOfSignature: getTypePredicateOfSignature,
resolveExternalModuleSymbol: resolveExternalModuleSymbol,
- tryGetThisTypeAt: function (node) {
+ tryGetThisTypeAt: function (node, includeGlobalThis) {
node = ts.getParseTreeNode(node);
- return node && tryGetThisTypeAt(node);
+ return node && tryGetThisTypeAt(node, includeGlobalThis);
},
getTypeArgumentConstraint: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
@@ -31169,10 +31439,10 @@
},
getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
};
- function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) {
+ function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
apparentArgumentCount = argumentCount;
- var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined;
+ var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
apparentArgumentCount = undefined;
return res;
}
@@ -31181,6 +31451,7 @@
var intersectionTypes = ts.createMap();
var literalTypes = ts.createMap();
var indexedAccessTypes = ts.createMap();
+ var conditionalTypes = ts.createMap();
var evolvingArrayTypes = [];
var undefinedProperties = ts.createMap();
var unknownSymbol = createSymbol(4 /* Property */, "unknown");
@@ -31191,9 +31462,9 @@
var errorType = createIntrinsicType(1 /* Any */, "error");
var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
- var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined");
+ var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */);
var nullType = createIntrinsicType(65536 /* Null */, "null");
- var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null");
+ var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */);
var stringType = createIntrinsicType(4 /* String */, "string");
var numberType = createIntrinsicType(8 /* Number */, "number");
var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
@@ -31219,6 +31490,7 @@
var voidType = createIntrinsicType(16384 /* Void */, "void");
var neverType = createIntrinsicType(131072 /* Never */, "never");
var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
+ var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */);
var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
@@ -31235,7 +31507,7 @@
var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
// The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
// in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
- anyFunctionType.flags |= 536870912 /* ContainsAnyFunctionType */;
+ anyFunctionType.objectFlags |= 524288 /* NonInferrableType */;
var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
@@ -31249,7 +31521,6 @@
var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
- var globals = ts.createSymbolTable();
/** Key is "/path/to/a.ts|/path/to/b.ts". */
var amalgamatedDuplicates;
var reverseMappedCache = ts.createMap();
@@ -31448,9 +31719,11 @@
var CheckMode;
(function (CheckMode) {
CheckMode[CheckMode["Normal"] = 0] = "Normal";
- CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive";
+ CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
- CheckMode[CheckMode["Contextual"] = 3] = "Contextual";
+ CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
+ CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
+ CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
})(CheckMode || (CheckMode = {}));
var CallbackCheck;
(function (CallbackCheck) {
@@ -31537,18 +31810,6 @@
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)
@@ -31728,7 +31989,7 @@
err.relatedInformation = err.relatedInformation || [];
if (ts.length(err.relatedInformation) >= 5)
continue;
- addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here));
+ ts.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) {
@@ -31806,7 +32067,7 @@
return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
}
function isGlobalSourceFile(node) {
- return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
+ return node.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning) {
@@ -31980,7 +32241,7 @@
// - 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 & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) {
+ if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 296 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -32022,14 +32283,14 @@
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
isInExternalModule = true;
// falls through
case 244 /* ModuleDeclaration */:
var moduleExports = getSymbolOfNode(location).exports;
- if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) {
+ if (location.kind === 284 /* 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 */)) {
@@ -32197,12 +32458,18 @@
// @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
// }
//
- if (location.parent && ts.isClassElement(location.parent)) {
+ // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
+ //
+ // type T = number;
+ // declare function y(x: T): any;
+ // @param(1 as T) // <-- T should resolve to the type alias outside of class C
+ // class C<T> {}
+ if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 240 /* ClassDeclaration */)) {
location = location.parent;
}
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
// js type aliases do not resolve names from their host, so skip past it
location = ts.getJSDocHost(location);
break;
@@ -32221,7 +32488,7 @@
}
if (!result) {
if (lastLocation) {
- ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */);
+ ts.Debug.assert(lastLocation.kind === 284 /* SourceFile */);
if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
return lastLocation.symbol;
}
@@ -32244,7 +32511,8 @@
!checkAndReportErrorForExtendingInterface(errorLocation) &&
!checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
!checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
- !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) {
+ !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
+ !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
var suggestion = void 0;
if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
@@ -32252,7 +32520,7 @@
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));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
}
}
}
@@ -32409,6 +32677,16 @@
}
return false;
}
+ function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
+ if (meaning & (67897832 /* Type */ & ~1920 /* Namespace */)) {
+ var symbol = resolveSymbol(resolveName(errorLocation, name, ~67897832 /* Type */ & 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
+ error(errorLocation, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here, ts.unescapeLeadingUnderscores(name));
+ return true;
+ }
+ }
+ return false;
+ }
function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) {
if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") {
@@ -32417,7 +32695,7 @@
}
var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
- var message = (name === "Promise" || name === "Symbol")
+ var message = isES2015OrLaterConstructorName(name)
? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later
: ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
@@ -32426,6 +32704,18 @@
}
return false;
}
+ function isES2015OrLaterConstructorName(n) {
+ switch (n) {
+ case "Promise":
+ case "Symbol":
+ case "Map":
+ case "WeakMap":
+ case "Set":
+ case "WeakSet":
+ return true;
+ }
+ return false;
+ }
function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) {
var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
@@ -32468,7 +32758,7 @@
}
}
if (diagnosticMessage) {
- addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
+ ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
}
}
}
@@ -32652,7 +32942,7 @@
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));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
}
}
else {
@@ -32972,22 +33262,14 @@
return undefined;
}
if (moduleNotFoundError) {
- // For relative paths, see if this was possibly a projectReference redirect
- if (ts.pathIsRelative(moduleReference)) {
- var sourceFile_1 = ts.getSourceFileOfNode(location);
- var redirects = sourceFile_1.redirectedReferences;
- if (redirects) {
- var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName));
- for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) {
- var ext = _a[_i];
- var probePath = normalizedTargetPath + ext;
- if (redirects.indexOf(probePath) >= 0) {
- error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath);
+ // See if this was possibly a projectReference redirect
+ if (resolvedModule) {
+ var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
+ if (redirect) {
+ error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
return undefined;
}
}
- }
- }
if (resolutionDiagnostic) {
error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
}
@@ -33054,7 +33336,7 @@
function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) {
var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
if (!dontResolveAlias && symbol) {
- if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) {
+ if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 284 /* SourceFile */)) {
var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
? "allowSyntheticDefaultImports"
: "esModuleInterop";
@@ -33327,9 +33609,11 @@
result.id = typeCount;
return result;
}
- function createIntrinsicType(kind, intrinsicName) {
+ function createIntrinsicType(kind, intrinsicName, objectFlags) {
+ if (objectFlags === void 0) { objectFlags = 0; }
var type = createType(kind);
type.intrinsicName = intrinsicName;
+ type.objectFlags = objectFlags;
return type;
}
function createBooleanType(trueFalseTypes) {
@@ -33400,7 +33684,7 @@
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
@@ -33640,10 +33924,10 @@
return node && getSymbolOfNode(node);
}
function hasExternalModuleSymbol(declaration) {
- return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isAmbientModule(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
- return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
var aliasesToMakeVisible;
@@ -34012,8 +34296,8 @@
context.inferTypeParameters = type.root.inferTypeParameters;
var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
context.inferTypeParameters = saveInferTypeParameters;
- var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context);
- var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context);
+ var trueTypeNode = typeToTypeNodeHelper(type.trueType, context);
+ var falseTypeNode = typeToTypeNodeHelper(type.falseType, context);
context.approximateLength += 15;
return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
}
@@ -34100,7 +34384,7 @@
var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
(symbol.parent || // is exported function symbol
ts.forEach(symbol.declarations, function (declaration) {
- return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
+ return declaration.parent.kind === 284 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
// typeof is allowed only for static/non local functions
@@ -34140,13 +34424,14 @@
}
function typeReferenceToTypeNode(type) {
var typeArguments = type.typeArguments || ts.emptyArray;
- if (type.target === globalArrayType) {
+ if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
if (context.flags & 2 /* WriteArrayAsGenericType */) {
var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
- return ts.createTypeReferenceNode("Array", [typeArgumentNode]);
+ return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
}
var elementType = typeToTypeNodeHelper(typeArguments[0], context);
- return ts.createArrayTypeNode(elementType);
+ var arrayType = ts.createArrayTypeNode(elementType);
+ return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, arrayType);
}
else if (type.target.objectFlags & 8 /* Tuple */) {
if (typeArguments.length > 0) {
@@ -34159,11 +34444,13 @@
ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
ts.createOptionalTypeNode(tupleConstituentNodes[i]);
}
- return ts.createTupleTypeNode(tupleConstituentNodes);
+ var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes);
+ return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
}
}
if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
- return ts.createTupleTypeNode([]);
+ var tupleTypeNode = ts.createTupleTypeNode([]);
+ return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
}
context.encounteredError = true;
return undefined; // TODO: GH#18217
@@ -34327,7 +34614,7 @@
context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
context.enclosingDeclaration = saveEnclosingDeclaration;
var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined;
- if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) {
+ if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
var signatures = getSignaturesOfType(propertyType, 0 /* Call */);
for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
var signature = signatures_1[_i];
@@ -34463,7 +34750,7 @@
var savedContextFlags = context.flags;
context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
- type.symbol.declarations[0] &&
+ type.symbol.declarations && type.symbol.declarations[0] &&
ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
typeParameterShadowsNameInScope(type, context);
var name = shouldUseGeneratedName
@@ -34482,7 +34769,7 @@
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */);
if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
- parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */);
+ parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 304 /* JSDocParameterTag */);
}
var parameterType = getTypeOfSymbol(parameterSymbol);
if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
@@ -34640,7 +34927,7 @@
return top;
}
function getSpecifierForModuleSymbol(symbol, context) {
- var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */);
+ var file = ts.getDeclarationOfKind(symbol, 284 /* SourceFile */);
if (file && file.moduleName !== undefined) {
// Use the amd name if it is available
return file.moduleName;
@@ -34893,7 +35180,7 @@
ts.isExternalModuleAugmentation(node.parent.parent);
}
function isDefaultBindingContext(location) {
- return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location);
+ return location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location);
}
function getNameOfSymbolFromNameType(symbol, context) {
var nameType = symbol.nameType;
@@ -34970,8 +35257,8 @@
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* 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));
@@ -34998,7 +35285,7 @@
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 !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
+ !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 284 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
return isGlobalSourceFile(parent);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
@@ -35040,7 +35327,7 @@
// Type parameters are always visible
case 150 /* TypeParameter */:
// Source file and namespace export are always visible
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 247 /* NamespaceExportDeclaration */:
return true;
// Export assignments do not create name bindings outside the module
@@ -35219,7 +35506,7 @@
if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
&& !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
&& isSpreadableProperty(prop)) {
- members.set(prop.escapedName, getSpreadSymbol(prop));
+ members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
}
}
var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
@@ -35288,17 +35575,8 @@
function getTypeForBindingElement(declaration) {
var pattern = declaration.parent;
var parentType = getTypeForBindingElementParent(pattern.parent);
- // If parent has the unknown (error) type, then so does this binding element
- if (parentType === errorType) {
- return errorType;
- }
- // If no type was specified or inferred for parent,
- // infer from the initializer of the binding element if one is present.
- // Otherwise, go with the undefined type of the parent.
- if (!parentType) {
- return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType;
- }
- if (isTypeAny(parentType)) {
+ // If no type or an any type was inferred for parent, infer that for the binding element
+ if (!parentType || isTypeAny(parentType)) {
return parentType;
}
// Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
@@ -35380,6 +35658,11 @@
if (optional === void 0) { optional = true; }
return strictNullChecks && optional ? getOptionalType(type) : type;
}
+ function isParameterOfContextuallyTypedFunction(node) {
+ return node.kind === 151 /* Parameter */ &&
+ (node.parent.kind === 196 /* FunctionExpression */ || node.parent.kind === 197 /* ArrowFunction */) &&
+ !!getContextualType(node.parent);
+ }
// Return the inferred type for a variable, parameter, or property declaration
function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
// A variable declared in a for..in statement is of type string, or of type keyof T when the
@@ -35455,8 +35738,9 @@
return containerObjectType;
}
}
- // Use the type of the initializer expression if one is present
- if (declaration.initializer) {
+ // Use the type of the initializer expression if one is present and the declaration is
+ // not a parameter of a contextually typed function
+ if (declaration.initializer && !isParameterOfContextuallyTypedFunction(declaration)) {
var type = checkDeclarationInitializer(declaration);
return addOptionality(type, isOptional);
}
@@ -35465,8 +35749,9 @@
// I.e <Elem attr /> is sugar for <Elem attr={true} />
return trueType;
}
- // If the declaration specifies a binding pattern, use the type implied by the binding pattern
- if (ts.isBindingPattern(declaration.name)) {
+ // If the declaration specifies a binding pattern and is not a parameter of a contextually
+ // typed function, use the type implied by the binding pattern
+ if (ts.isBindingPattern(declaration.name) && !isParameterOfContextuallyTypedFunction(declaration)) {
return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
}
// No type specified and nothing can be inferred
@@ -35522,7 +35807,7 @@
definedInConstructor = true;
}
}
- var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217
+ var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
type = getUnionType(sourceTypes, 2 /* Subtype */);
}
var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
@@ -35673,7 +35958,7 @@
function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
var members = ts.createSymbolTable();
var stringIndexInfo;
- var objectFlags = 128 /* ObjectLiteral */;
+ var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
ts.forEach(pattern.elements, function (e) {
var name = e.propertyName || e.name;
if (e.dotDotDotToken) {
@@ -35694,7 +35979,6 @@
members.set(symbol.escapedName, symbol);
});
var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
- result.flags |= 268435456 /* ContainsObjectLiteral */;
result.objectFlags |= objectFlags;
if (includePatternInType) {
result.pattern = pattern;
@@ -35778,7 +36062,16 @@
}
function getTypeOfVariableOrParameterOrProperty(symbol) {
var links = getSymbolLinks(symbol);
- return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol));
+ if (!links.type) {
+ var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
+ // For a contextually typed parameter it is possible that a type has already
+ // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
+ // to preserve this type.
+ if (!links.type) {
+ links.type = type;
+ }
+ }
+ return links.type;
}
function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
// Handle prototype property
@@ -35811,19 +36104,19 @@
}
return type_1;
}
- if (declaration.kind === 254 /* ExportAssignment */) {
- return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
- }
// Handle variable, parameter or property
if (!pushTypeResolution(symbol, 0 /* Type */)) {
// Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
if (symbol.flags & 512 /* ValueModule */) {
return getTypeOfFuncClassEnumModule(symbol);
}
- return errorType;
+ return reportCircularityError(symbol);
}
var type;
- if (ts.isInJSFile(declaration) &&
+ if (declaration.kind === 254 /* ExportAssignment */) {
+ type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
+ }
+ else if (ts.isInJSFile(declaration) &&
(ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) {
type = getWidenedTypeFromAssignmentDeclaration(symbol);
}
@@ -35878,7 +36171,7 @@
if (symbol.flags & 512 /* ValueModule */) {
return getTypeOfFuncClassEnumModule(symbol);
}
- type = reportCircularityError(symbol);
+ return reportCircularityError(symbol);
}
return type;
}
@@ -36056,15 +36349,19 @@
return links.type;
}
function reportCircularityError(symbol) {
+ var declaration = symbol.valueDeclaration;
// Check if variable has type annotation that circularly references the variable itself
- if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) {
+ if (ts.getEffectiveTypeAnnotationNode(declaration)) {
error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
return errorType;
}
- // Otherwise variable has initializer that circularly references the variable itself
- if (noImplicitAny) {
+ // Check if variable has initializer that circularly references the variable itself
+ if (noImplicitAny && (declaration.kind !== 151 /* Parameter */ || declaration.initializer)) {
error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
}
+ // Circularities could also result from parameters in function expressions that end up
+ // having themselves as contextual types following type argument inference. In those cases
+ // we have already reported an implicit any error so we don't report anything here.
return anyType;
}
function getTypeOfSymbol(symbol) {
@@ -36140,15 +36437,15 @@
case 155 /* MethodSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 308 /* JSDocTemplateTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 181 /* MappedType */:
case 175 /* ConditionalType */:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -36269,7 +36566,7 @@
ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
}
}
- addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
+ ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
}
return type.resolvedBaseConstructorType = errorType;
}
@@ -36280,7 +36577,7 @@
function getBaseTypes(type) {
if (!type.resolvedBaseTypes) {
if (type.objectFlags & 8 /* Tuple */) {
- type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))];
+ type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)];
}
else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
if (type.symbol.flags & 32 /* Class */) {
@@ -36645,7 +36942,7 @@
}
return false;
}
- /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */
+ /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
function isThislessTypeParameter(node) {
var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
return !constraint || isThislessType(constraint);
@@ -36688,6 +36985,8 @@
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
case 157 /* Constructor */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
return isThislessFunctionLikeDeclaration(declaration);
}
}
@@ -37019,8 +37318,18 @@
return sig;
}
function cloneSignature(sig) {
- return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
+ var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
/*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes);
+ result.target = sig.target;
+ result.mapper = sig.mapper;
+ return result;
+ }
+ function createUnionSignature(signature, unionSignatures) {
+ var result = cloneSignature(signature);
+ result.unionSignatures = unionSignatures;
+ result.target = undefined;
+ result.mapper = undefined;
+ return result;
}
function getExpandedParameters(sig) {
if (sig.hasRestParameter) {
@@ -37129,9 +37438,8 @@
var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */);
thisParameter = createSymbolWithType(signature.thisParameter, thisType);
}
- s = cloneSignature(signature);
+ s = createUnionSignature(signature, unionSignatures);
s.thisParameter = thisParameter;
- s.unionSignatures = unionSignatures;
}
(result || (result = [])).push(s);
}
@@ -37246,13 +37554,22 @@
function unionSpreadIndexInfos(info1, info2) {
return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
}
- function includeMixinType(type, types, index) {
+ function findMixins(types) {
+ var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
+ var mixinFlags = ts.map(types, isMixinConstructorType);
+ if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
+ var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
+ mixinFlags[firstMixinIndex] = false;
+ }
+ return mixinFlags;
+ }
+ function includeMixinType(type, types, mixinFlags, index) {
var mixedTypes = [];
for (var i = 0; i < types.length; i++) {
if (i === index) {
mixedTypes.push(type);
}
- else if (isMixinConstructorType(types[i])) {
+ else if (mixinFlags[i]) {
mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
}
}
@@ -37266,7 +37583,8 @@
var stringIndexInfo;
var numberIndexInfo;
var types = type.types;
- var mixinCount = ts.countWhere(types, isMixinConstructorType);
+ var mixinFlags = findMixins(types);
+ var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
var _loop_6 = function (i) {
var t = type.types[i];
// When an intersection type contains mixin constructor types, the construct signatures from
@@ -37274,12 +37592,12 @@
// other construct signatures in the intersection type. For example, the intersection type
// '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
// 'new(s: string) => A & B'.
- if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) {
+ if (!mixinFlags[i]) {
var signatures = getSignaturesOfType(t, 1 /* Construct */);
if (signatures.length && mixinCount > 0) {
signatures = ts.map(signatures, function (s) {
var clone = cloneSignature(s);
- clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i);
+ clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
return clone;
});
}
@@ -37323,6 +37641,15 @@
var stringIndexInfo = void 0;
if (symbol.exports) {
members = getExportsOfSymbol(symbol);
+ if (symbol === globalThisSymbol) {
+ var varsOnly_1 = ts.createMap();
+ members.forEach(function (p) {
+ if (!(p.flags & 418 /* BlockScoped */)) {
+ varsOnly_1.set(p.escapedName, p);
+ }
+ });
+ members = varsOnly_1;
+ }
}
setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
if (symbol.flags & 32 /* Class */) {
@@ -37622,7 +37949,7 @@
var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
- return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected);
+ return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
});
}
function getAllPossiblePropertiesOfTypes(types) {
@@ -37655,6 +37982,9 @@
return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
}
function getConstraintOfIndexedAccess(type) {
+ return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
+ }
+ function getConstraintFromIndexedAccess(type) {
var objectType = getConstraintOfType(type.objectType) || type.objectType;
if (objectType !== type.objectType) {
var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType);
@@ -37667,13 +37997,13 @@
}
function getDefaultConstraintOfConditionalType(type) {
if (!type.resolvedDefaultConstraint) {
- var rootTrueType = type.root.trueType;
- var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */)
- ? rootTrueType
- : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */
- ? rootTrueType.typeVariable
- : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]);
- type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]);
+ // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
+ // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
+ // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
+ // in effect treating `any` like `never` rather than `unknown` in this location.
+ var trueConstraint = getInferredTrueTypeFromConditionalType(type);
+ var falseConstraint = type.falseType;
+ type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
}
return type.resolvedDefaultConstraint;
}
@@ -37683,7 +38013,13 @@
// with its constraint. We do this because if the constraint is a union type it will be distributed
// over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
// removes 'undefined' from T.
- if (type.root.isDistributive) {
+ // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
+ // as the constraint for all type params (check type included) have been replace with `unknown`, which
+ // is going to produce even more false positive/negative results than the distribute constraint already does.
+ // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
+ // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
+ // likely doesn't need to exist.
+ if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
var simplified = getSimplifiedType(type.checkType);
var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
if (constraint && constraint !== type.checkType) {
@@ -37696,9 +38032,12 @@
}
return undefined;
}
- function getConstraintOfConditionalType(type) {
+ function getConstraintFromConditionalType(type) {
return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
}
+ function getConstraintOfConditionalType(type) {
+ return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
+ }
function getUnionConstraintOfIntersection(type, targetIsUnion) {
var constraints;
var hasDisjointDomainType = false;
@@ -37772,18 +38111,31 @@
if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
return circularConstraintType;
}
- if (constraintDepth === 50) {
+ if (constraintDepth >= 50) {
// We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
// very high likelyhood we're dealing with an infinite generic type that perpetually generates
// new type identities as we descend into it. We stop the recursion here and mark this type
// and the outer types as having circular constraints.
+ error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
nonTerminating = true;
return t.immediateBaseConstraint = noConstraintType;
}
constraintDepth++;
var result = computeBaseConstraint(getSimplifiedType(t));
constraintDepth--;
- if (!popTypeResolution() || nonTerminating) {
+ if (!popTypeResolution()) {
+ if (t.flags & 262144 /* TypeParameter */) {
+ var errorNode = getConstraintDeclaration(t);
+ if (errorNode) {
+ var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
+ if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
+ }
+ }
+ }
+ result = circularConstraintType;
+ }
+ if (nonTerminating) {
result = circularConstraintType;
}
t.immediateBaseConstraint = result || noConstraintType;
@@ -37825,8 +38177,11 @@
return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined;
}
if (t.flags & 16777216 /* Conditional */) {
- var constraint = getConstraintOfConditionalType(t);
- return constraint && getBaseConstraint(constraint);
+ var constraint = getConstraintFromConditionalType(t);
+ constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
+ var result = constraint && getBaseConstraint(constraint);
+ constraintDepth--;
+ return result;
}
if (t.flags & 33554432 /* Substitution */) {
return getBaseConstraint(t.substitute);
@@ -37887,7 +38242,7 @@
var typeVariable = getHomomorphicTypeVariable(type);
if (typeVariable) {
var constraint = getConstraintOfTypeParameter(typeVariable);
- if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) {
+ if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
var mapper = makeUnaryTypeMapper(typeVariable, constraint);
return instantiateType(type, combineTypeMappers(mapper, type.mapper));
}
@@ -37905,7 +38260,7 @@
t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
t.flags & 132 /* StringLike */ ? globalStringType :
t.flags & 296 /* NumberLike */ ? globalNumberType :
- t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) :
+ t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ESNext */) :
t.flags & 528 /* BooleanLike */ ? globalBooleanType :
t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
@@ -37913,7 +38268,7 @@
t;
}
function createUnionOrIntersectionProperty(containingType, name) {
- var props;
+ var propSet = ts.createMap();
var indexTypes;
var isUnion = containingType.flags & 1048576 /* Union */;
var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0;
@@ -37929,7 +38284,10 @@
var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
if (prop && !(modifiers & excludeModifiers)) {
commonFlags &= prop.flags;
- props = ts.appendIfUnique(props, prop);
+ var id = "" + getSymbolId(prop);
+ if (!propSet.has(id)) {
+ propSet.set(id, prop);
+ }
checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
(!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) |
(modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) |
@@ -37951,9 +38309,10 @@
}
}
}
- if (!props) {
+ if (!propSet.size) {
return undefined;
}
+ var props = ts.arrayFrom(propSet.values());
if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) {
return props[0];
}
@@ -38125,10 +38484,10 @@
function isJSDocOptionalParameter(node) {
return ts.isInJSFile(node) && (
// node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
- node.type && node.type.kind === 288 /* JSDocOptionalType */
+ node.type && node.type.kind === 293 /* JSDocOptionalType */
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -38162,7 +38521,7 @@
return false;
}
var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}
function createIdentifierTypePredicate(parameterName, parameterIndex, type) {
return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
@@ -38396,32 +38755,23 @@
}
}
signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
- createTypePredicateFromTypePredicateNode(type, signature.declaration) :
+ createTypePredicateFromTypePredicateNode(type, signature) :
jsdocPredicate || noTypePredicate;
}
ts.Debug.assert(!!signature.resolvedTypePredicate);
}
return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
}
- function createTypePredicateFromTypePredicateNode(node, func) {
+ function createTypePredicateFromTypePredicateNode(node, signature) {
var parameterName = node.parameterName;
var type = getTypeFromTypeNode(node.type);
if (parameterName.kind === 72 /* Identifier */) {
- return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type);
+ return createIdentifierTypePredicate(parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), 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 === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) {
- return i;
- }
- }
- return -1;
- }
function getReturnTypeOfSignature(signature) {
if (!signature.resolvedReturnType) {
if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
@@ -38493,8 +38843,19 @@
}
return undefined;
}
- function getSignatureInstantiation(signature, typeArguments, isJavascript) {
- return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ if (inferredTypeParameters) {
+ var returnSignature = getSingleCallSignature(getReturnTypeOfSignature(instantiatedSignature));
+ if (returnSignature) {
+ var newReturnSignature = cloneSignature(returnSignature);
+ newReturnSignature.typeParameters = inferredTypeParameters;
+ var newInstantiatedSignature = cloneSignature(instantiatedSignature);
+ newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
+ return newInstantiatedSignature;
+ }
+ }
+ return instantiatedSignature;
}
function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
@@ -38689,10 +39050,10 @@
for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
var type = types_5[_i];
if (!(type.flags & excludeKinds)) {
- result |= type.flags;
+ result |= ts.getObjectFlags(type);
}
}
- return result & 939524096 /* PropagatingFlags */;
+ return result & 917504 /* PropagatingFlags */;
}
function createTypeReference(target, typeArguments) {
var id = getTypeListId(typeArguments);
@@ -38700,7 +39061,7 @@
if (!type) {
type = createObjectType(4 /* Reference */, target.symbol);
target.instantiations.set(id, type);
- type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
+ type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
type.target = target;
type.typeArguments = typeArguments;
}
@@ -38866,7 +39227,7 @@
}
function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
- if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
+ if (symbol.valueDeclaration && symbol.valueDeclaration.parent && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
if (jsdocType) {
return jsdocType;
@@ -38887,6 +39248,9 @@
}
}
function getSubstitutionType(typeVariable, substitute) {
+ if (substitute.flags & 3 /* AnyOrUnknown */) {
+ return typeVariable;
+ }
var result = createType(33554432 /* Substitution */);
result.typeVariable = typeVariable;
result.substitute = substitute;
@@ -38902,7 +39266,7 @@
}
function getConstrainedTypeVariable(typeVariable, node) {
var constraints;
- while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) {
+ while (node && !ts.isStatement(node) && node.kind !== 296 /* JSDocComment */) {
var parent = node.parent;
if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) {
var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
@@ -39134,19 +39498,19 @@
function createIterableIteratorType(iteratedType) {
return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]);
}
- function createArrayType(elementType) {
- return createTypeFromGenericGlobalType(globalArrayType, [elementType]);
- }
- function createReadonlyArrayType(elementType) {
- return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]);
+ function createArrayType(elementType, readonly) {
+ return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
}
function getTypeFromArrayTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType));
+ links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType), isReadonlyTypeOperator(node.parent));
}
return links.resolvedType;
}
+ function isReadonlyTypeOperator(node) {
+ return ts.isTypeOperatorNode(node) && node.operator === 133 /* ReadonlyKeyword */;
+ }
// We represent tuple types as type references to synthesized generic interface types created by
// this function. The types are of the form:
//
@@ -39154,7 +39518,7 @@
//
// 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, minLength, hasRestElement, associatedNames) {
+ function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
var typeParameters;
var properties = [];
var maxLength = hasRestElement ? arity - 1 : arity;
@@ -39163,7 +39527,7 @@
for (var i = 0; i < arity; i++) {
var typeParameter = typeParameters[i] = createTypeParameter();
if (i < maxLength) {
- var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i);
+ var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
property.type = typeParameter;
properties.push(property);
}
@@ -39193,25 +39557,27 @@
type.declaredNumberIndexInfo = undefined;
type.minLength = minLength;
type.hasRestElement = hasRestElement;
+ type.readonly = readonly;
type.associatedNames = associatedNames;
return type;
}
- function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) {
- var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
+ function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
+ var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
var type = tupleTypes.get(key);
if (!type) {
- tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames));
+ tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames));
}
return type;
}
- function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) {
+ function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) {
if (minLength === void 0) { minLength = elementTypes.length; }
if (hasRestElement === void 0) { hasRestElement = false; }
+ if (readonly === void 0) { readonly = false; }
var arity = elementTypes.length;
if (arity === 1 && hasRestElement) {
- return createArrayType(elementTypes[0]);
+ return createArrayType(elementTypes[0], readonly);
}
- var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames);
+ var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames);
return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
}
function getTypeFromTupleTypeNode(node) {
@@ -39224,7 +39590,7 @@
var type = getTypeFromTypeNode(n);
return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type;
});
- links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1);
+ links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1, isReadonlyTypeOperator(node.parent));
}
return links.resolvedType;
}
@@ -39234,7 +39600,7 @@
// don't slice off rest element
index = Math.min(index, getTypeReferenceArity(type) - 1);
}
- return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index));
+ return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index));
}
function getTypeFromOptionalTypeNode(node) {
var type = getTypeFromTypeNode(node.type);
@@ -39292,12 +39658,14 @@
// intersections of unit types into 'never' upon construction, but deferring the reduction makes it
// easier to reason about their origin.
if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) {
- includes |= flags & ~939524096 /* ConstructionFlags */;
+ includes |= flags & 1835007 /* IncludesMask */;
+ if (flags & 66846720 /* StructuredOrInstantiable */)
+ includes |= 262144 /* IncludesStructuredOrInstantiable */;
if (type === wildcardType)
- includes |= 268435456 /* Wildcard */;
+ includes |= 4194304 /* IncludesWildcard */;
if (!strictNullChecks && flags & 98304 /* Nullable */) {
- if (!(flags & 134217728 /* ContainsWideningType */))
- includes |= 134217728 /* NonWideningType */;
+ if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */))
+ includes |= 2097152 /* IncludesNonWideningType */;
}
else {
var len = typeSet.length;
@@ -39318,17 +39686,6 @@
}
return includes;
}
- function isSubtypeOfAny(source, targets) {
- for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
- var target = targets_1[_i];
- if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
- !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
- isTypeDerivedFrom(source, target))) {
- return true;
- }
- }
- return false;
- }
function isSetOfLiteralsFromSameEnum(types) {
var first = types[0];
if (first.flags & 1024 /* EnumLiteral */) {
@@ -39343,18 +39700,43 @@
}
return false;
}
- function removeSubtypes(types) {
- if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) {
- return;
+ function removeSubtypes(types, primitivesOnly) {
+ var len = types.length;
+ if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
+ return true;
}
- var i = types.length;
+ var i = len;
+ var count = 0;
while (i > 0) {
i--;
- if (isSubtypeOfAny(types[i], types)) {
+ var source = types[i];
+ for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
+ var target = types_7[_i];
+ if (source !== target) {
+ if (count === 100000) {
+ // After 100000 subtype checks we estimate the remaining amount of work by assuming the
+ // same ratio of checks per element. If the estimated number of remaining type checks is
+ // greater than an upper limit we deem the union type too complex to represent. The
+ // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
+ // caps union types at 5000 unique literal types and 1000 unique object types.
+ var estimatedCount = (count / (len - i)) * len;
+ if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
+ error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
+ return false;
+ }
+ }
+ count++;
+ if (isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
+ !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
+ isTypeDerivedFrom(source, target))) {
ts.orderedRemoveItemAt(types, i);
+ break;
}
}
}
+ }
+ return true;
+ }
function removeRedundantLiteralTypes(types, includes) {
var i = types.length;
while (i > 0) {
@@ -39389,25 +39771,27 @@
var includes = addTypesToUnion(typeSet, 0, types);
if (unionReduction !== 0 /* None */) {
if (includes & 3 /* AnyOrUnknown */) {
- return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType;
+ return includes & 1 /* Any */ ? includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
}
switch (unionReduction) {
case 1 /* Literal */:
- if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) {
+ if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
removeRedundantLiteralTypes(typeSet, includes);
}
break;
case 2 /* Subtype */:
- removeSubtypes(typeSet);
+ if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
+ return errorType;
+ }
break;
}
if (typeSet.length === 0) {
- return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType :
- includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType :
+ return includes & 65536 /* Null */ ? includes & 2097152 /* IncludesNonWideningType */ ? nullType : nullWideningType :
+ includes & 32768 /* Undefined */ ? includes & 2097152 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
neverType;
}
}
- return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments);
+ return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments);
}
function getUnionTypePredicate(signatures) {
var first;
@@ -39444,7 +39828,7 @@
: !ts.isIdentifierTypePredicate(b);
}
// This function assumes the constituent type list is sorted and deduplicated.
- function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) {
+ function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
if (types.length === 0) {
return neverType;
}
@@ -39454,11 +39838,10 @@
var id = getTypeListId(types);
var type = unionTypes.get(id);
if (!type) {
- var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
- type = createType(1048576 /* Union */ | propagatedFlags);
+ type = createType(1048576 /* Union */);
unionTypes.set(id, type);
+ type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
type.types = types;
- type.primitiveTypesOnly = primitiveTypesOnly;
/*
Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
@@ -39484,16 +39867,16 @@
return addTypesToIntersection(typeSet, includes, type.types);
}
if (isEmptyAnonymousObjectType(type)) {
- if (!(includes & 536870912 /* EmptyObject */)) {
- includes |= 536870912 /* EmptyObject */;
+ if (!(includes & 8388608 /* IncludesEmptyObject */)) {
+ includes |= 8388608 /* IncludesEmptyObject */;
typeSet.push(type);
}
}
else {
- includes |= flags & ~939524096 /* ConstructionFlags */;
+ includes |= flags & 1835007 /* IncludesMask */;
if (flags & 3 /* AnyOrUnknown */) {
if (type === wildcardType)
- includes |= 268435456 /* Wildcard */;
+ includes |= 4194304 /* IncludesWildcard */;
}
else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) {
typeSet.push(type);
@@ -39504,8 +39887,8 @@
// Add the given types to the given type set. Order is preserved, freshness is removed from literal
// types, duplicates are removed, and nested types of the given kind are flattened into the set.
function addTypesToIntersection(typeSet, includes, types) {
- for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
- var type = types_7[_i];
+ for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
+ var type = types_8[_i];
includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
}
return includes;
@@ -39548,7 +39931,7 @@
// 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 & 1048576 /* Union */) && t.primitiveTypesOnly; });
+ var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); });
if (index < 0) {
return false;
}
@@ -39557,7 +39940,7 @@
// the unionTypes array.
while (i < types.length) {
var t = types[i];
- if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) {
+ if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) {
(unionTypes || (unionTypes = [types[index]])).push(t);
ts.orderedRemoveItemAt(types, i);
}
@@ -39586,7 +39969,7 @@
}
}
// Finally replace the first union with the result
- types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true);
+ types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */);
return true;
}
// We normalize combinations of intersection and union types based on the distributive property of the '&'
@@ -39606,7 +39989,7 @@
return neverType;
}
if (includes & 1 /* Any */) {
- return includes & 268435456 /* Wildcard */ ? wildcardType : anyType;
+ return includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType;
}
if (!strictNullChecks && includes & 98304 /* Nullable */) {
return includes & 32768 /* Undefined */ ? undefinedType : nullType;
@@ -39617,7 +40000,7 @@
includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
removeRedundantPrimitiveTypes(typeSet, includes);
}
- if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) {
+ if (includes & 8388608 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
}
if (typeSet.length === 0) {
@@ -39642,9 +40025,9 @@
var id = getTypeListId(typeSet);
var type = intersectionTypes.get(id);
if (!type) {
- var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */);
- type = createType(2097152 /* Intersection */ | propagatedFlags);
+ type = createType(2097152 /* Intersection */);
intersectionTypes.set(id, type);
+ type.objectFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */);
type.types = typeSet;
type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
type.aliasTypeArguments = aliasTypeArguments;
@@ -39699,7 +40082,7 @@
return neverType;
}
function getLiteralTypeFromProperties(type, include) {
- return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); }));
+ return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
}
function getNonEnumNumberIndexInfo(type) {
var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
@@ -39741,6 +40124,9 @@
? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
: errorType;
break;
+ case 133 /* ReadonlyKeyword */:
+ links.resolvedType = getTypeFromTypeNode(node.type);
+ break;
}
}
return links.resolvedType; // TODO: GH#18217
@@ -39843,7 +40229,10 @@
return anyType;
}
if (accessExpression && !isConstEnumObjectType(objectType)) {
- if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
+ if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
+ error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
+ }
+ else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
}
@@ -39895,7 +40284,7 @@
: accessNode;
}
function isGenericObjectType(type) {
- return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */);
+ return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 131072 /* GenericMappedType */);
}
function isGenericIndexType(type) {
return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */);
@@ -39941,12 +40330,15 @@
// that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
// construct the type Box<T[X]>.
if (isGenericMappedType(objectType)) {
- var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
- var templateMapper = combineTypeMappers(objectType.mapper, mapper);
- return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType);
+ return type.simplified = mapType(substituteIndexedMappedType(objectType, type.indexType), getSimplifiedType);
}
return type.simplified = type;
}
+ function substituteIndexedMappedType(objectType, index) {
+ var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
+ var templateMapper = combineTypeMappers(objectType.mapper, mapper);
+ return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
+ }
function getIndexedAccessType(objectType, indexType, accessNode, missingType) {
if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; }
if (objectType === wildcardType || indexType === wildcardType) {
@@ -40028,13 +40420,48 @@
function getActualTypeVariable(type) {
return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type;
}
+ /**
+ * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
+ */
+ function isIntersectionEmpty(type1, type2) {
+ return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
+ }
function getConditionalType(root, mapper) {
var checkType = instantiateType(root.checkType, mapper);
var extendsType = instantiateType(root.extendsType, mapper);
if (checkType === wildcardType || extendsType === wildcardType) {
return wildcardType;
}
- var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */);
+ var trueType = instantiateType(root.trueType, mapper);
+ var falseType = instantiateType(root.falseType, mapper);
+ var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType);
+ var result = conditionalTypes.get(instantiationId);
+ if (result) {
+ return result;
+ }
+ var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType);
+ conditionalTypes.set(instantiationId, newResult);
+ return newResult;
+ }
+ function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) {
+ // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
+ if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
+ if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
+ return trueType;
+ }
+ else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
+ return neverType;
+ }
+ }
+ else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
+ if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
+ return neverType;
+ }
+ else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
+ return falseType;
+ }
+ }
+ var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */);
var combinedMapper;
if (root.inferTypeParameters) {
var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
@@ -40044,25 +40471,25 @@
// types rules (i.e. proper contravariance) for inferences.
inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
}
- combinedMapper = combineTypeMappers(mapper, context);
+ combinedMapper = combineTypeMappers(mapper, context.mapper);
}
// Instantiate the extends type including inferences for 'infer T' type parameters
var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
// We attempt to resolve the conditional type only when the check and extends types are non-generic
- if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */)) {
+ if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */)) {
if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) {
- return instantiateType(root.trueType, mapper);
+ return trueType;
}
// Return union of trueType and falseType for 'any' since it matches anything
if (checkType.flags & 1 /* Any */) {
- return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]);
+ return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), falseType]);
}
- // Return falseType for a definitely false extends check. We check an instantations of the two
+ // Return falseType for a definitely false extends check. We check an instantiations of the two
// types with type parameters mapped to the wildcard type, the most permissive instantiations
// possible (the wildcard type is assignable to and from all types). If those are not related,
- // then no instatiations will be and we can just return the false branch type.
+ // then no instantiations will be and we can just return the false branch type.
if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) {
- return instantiateType(root.falseType, mapper);
+ return falseType;
}
// Return trueType for a definitely true extends check. We check instantiations of the two
// types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
@@ -40074,6 +40501,9 @@
}
}
// Return a deferred type for a check that is neither definitely true nor definitely false
+ return getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType);
+ }
+ function getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType) {
var erasedCheckType = getActualTypeVariable(checkType);
var result = createType(16777216 /* Conditional */);
result.root = root;
@@ -40081,15 +40511,14 @@
result.extendsType = extendsType;
result.mapper = mapper;
result.combinedMapper = combinedMapper;
+ result.trueType = trueType;
+ result.falseType = falseType;
result.aliasSymbol = root.aliasSymbol;
result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
return result;
}
- function getTrueTypeFromConditionalType(type) {
- return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
- }
- function getFalseTypeFromConditionalType(type) {
- return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
+ function getInferredTrueTypeFromConditionalType(type) {
+ return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper || type.mapper));
}
function getInferTypeParameters(node) {
var result;
@@ -40258,7 +40687,7 @@
* this function should be called in a left folding style, with left = previous result of getSpreadType
* and right = the new element to be spread.
*/
- function getSpreadType(left, right, symbol, typeFlags, objectFlags) {
+ function getSpreadType(left, right, symbol, objectFlags, readonly) {
if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
return anyType;
}
@@ -40272,10 +40701,10 @@
return left;
}
if (left.flags & 1048576 /* Union */) {
- return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); });
+ return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
}
if (right.flags & 1048576 /* Union */) {
- return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); });
+ return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
}
if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
return left;
@@ -40291,7 +40720,7 @@
var types = left.types;
var lastLeft = types[types.length - 1];
if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
- return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)]));
+ return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
}
}
return getIntersectionType([left, right]);
@@ -40315,7 +40744,7 @@
skippedPrivateMembers.set(rightProp.escapedName, true);
}
else if (isSpreadableProperty(rightProp)) {
- members.set(rightProp.escapedName, getSpreadSymbol(rightProp));
+ members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
}
}
for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
@@ -40339,12 +40768,11 @@
}
}
else {
- members.set(leftProp.escapedName, getSpreadSymbol(leftProp));
+ members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
}
}
- var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo));
- spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags;
- spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
+ var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
+ spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
return spread;
}
/** We approximate own properties as non-methods plus methods that are inside the object literal */
@@ -40352,25 +40780,21 @@
return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
!prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); });
}
- function getSpreadSymbol(prop) {
- var isReadonly = isReadonlySymbol(prop);
+ function getSpreadSymbol(prop, readonly) {
var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
- if (!isReadonly && !isSetonlyAccessor) {
+ if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
return prop;
}
var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
- var result = createSymbol(flags, prop.escapedName);
+ var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
result.declarations = prop.declarations;
result.nameType = prop.nameType;
result.syntheticOrigin = prop;
return result;
}
- function getNonReadonlyIndexSignature(index) {
- if (index && index.isReadonly) {
- return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration);
- }
- return index;
+ function getIndexInfoWithReadonly(info, readonly) {
+ return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
}
function createLiteralType(flags, value, symbol) {
var type = createType(flags);
@@ -40458,8 +40882,8 @@
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 120 /* AnyKeyword */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return anyType;
case 143 /* UnknownKeyword */:
return unknownType;
@@ -40506,23 +40930,23 @@
return getTypeFromUnionTypeNode(node);
case 174 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return getTypeFromJSDocNullableTypeNode(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return addOptionality(getTypeFromTypeNode(node.type));
case 177 /* ParenthesizedType */:
case 172 /* RestType */:
- case 287 /* JSDocNonNullableType */:
- case 283 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 288 /* JSDocTypeExpression */:
return getTypeFromTypeNode(node.type);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 297 /* JSDocTypeLiteral */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 179 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
@@ -40598,16 +41022,8 @@
* Maps forward-references to later types parameters to the empty object type.
* This is used during inference when instantiating type parameter defaults.
*/
- function createBackreferenceMapper(typeParameters, index) {
- return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; };
- }
- function isInferenceContext(mapper) {
- return !!mapper.typeParameters;
- }
- function cloneTypeMapper(mapper) {
- return mapper && isInferenceContext(mapper) ?
- createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) :
- mapper;
+ function createBackreferenceMapper(context, index) {
+ return function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? emptyObjectType : t; };
}
function combineTypeMappers(mapper1, mapper2) {
if (!mapper1)
@@ -40690,7 +41106,7 @@
}
// 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) & (2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */));
+ var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */));
result.declarations = symbol.declarations;
result.parent = symbol.parent;
result.target = symbol;
@@ -40786,7 +41202,7 @@
function getHomomorphicTypeVariable(type) {
var constraintType = getConstraintTypeFromMappedType(type);
if (constraintType.flags & 4194304 /* Index */) {
- var typeVariable = constraintType.type;
+ var typeVariable = getActualTypeVariable(constraintType.type);
if (typeVariable.flags & 262144 /* TypeParameter */) {
return typeVariable;
}
@@ -40808,30 +41224,27 @@
if (typeVariable) {
var mappedTypeVariable = instantiateType(typeVariable, mapper);
if (typeVariable !== mappedTypeVariable) {
- // If we are already in the process of creating an instantiation of this mapped type,
- // return the error type. This situation only arises if we are instantiating the mapped
- // type for an array or tuple type, as we then need to eagerly resolve the (possibly
- // circular) element type(s).
- if (type.instantiating) {
- return errorType;
- }
- type.instantiating = true;
- var result = mapType(mappedTypeVariable, function (t) {
- if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) {
+ return mapType(mappedTypeVariable, function (t) {
+ if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
var replacementMapper = createReplacementMapper(typeVariable, t, mapper);
- return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
- isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
+ return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
instantiateAnonymousType(type, replacementMapper);
}
return t;
});
- type.instantiating = false;
- return result;
}
}
return instantiateAnonymousType(type, mapper);
}
+ function getModifiedReadonlyState(state, modifiers) {
+ return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
+ }
+ function instantiateMappedArrayType(arrayType, mappedType, mapper) {
+ var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
+ return elementType === errorType ? errorType :
+ createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
+ }
function instantiateMappedTupleType(tupleType, mappedType, mapper) {
var minLength = tupleType.target.minLength;
var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) {
@@ -40841,7 +41254,9 @@
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);
+ var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
+ return ts.contains(elementTypes, errorType) ? errorType :
+ createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames);
}
function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key]));
@@ -40907,6 +41322,7 @@
// We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
// with a combination of infinite generic types that perpetually generate new type identities. We stop
// the recursion here by yielding the error type.
+ error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
return errorType;
}
instantiationDepth++;
@@ -40958,7 +41374,17 @@
return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
}
if (flags & 33554432 /* Substitution */) {
- return instantiateType(type.typeVariable, mapper);
+ var maybeVariable = instantiateType(type.typeVariable, mapper);
+ if (maybeVariable.flags & 8650752 /* TypeVariable */) {
+ return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
+ }
+ else {
+ var sub = instantiateType(type.substitute, mapper);
+ if (sub.flags & 3 /* AnyOrUnknown */ || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
+ return maybeVariable;
+ }
+ return sub;
+ }
}
return type;
}
@@ -40967,8 +41393,20 @@
type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
}
function getRestrictiveInstantiation(type) {
- return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
- type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper));
+ if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
+ return type;
+ }
+ if (type.restrictiveInstantiation) {
+ return type.restrictiveInstantiation;
+ }
+ type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
+ // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
+ // which is redundant - we'll produce new type identities, but all type params have already been mapped.
+ // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
+ // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
+ // are constrained to `unknown` and produce tons of false positives/negatives!
+ type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
+ return type.restrictiveInstantiation;
}
function instantiateIndexInfo(info, mapper) {
return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
@@ -41167,7 +41605,7 @@
var resultObj = {};
checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj);
var diagnostic = resultObj.error;
- addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
return true;
}
}
@@ -41202,7 +41640,7 @@
checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj);
if (resultObj.error) {
if (target.symbol && ts.length(target.symbol.declarations)) {
- addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
+ ts.addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
}
return true;
}
@@ -41249,13 +41687,13 @@
undefined;
if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
issuedElaboration = true;
- addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
+ ts.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))) {
var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
- addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
+ ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
}
}
}
@@ -41326,7 +41764,7 @@
// child is of the type of the expression
return { errorNode: child, innerExpression: child.expression, nameType: nameType };
case 11 /* JsxText */:
- if (child.containsOnlyWhiteSpaces) {
+ if (child.containsOnlyTriviaWhiteSpaces) {
break; // Whitespace only jsx text isn't real jsx text
}
// child is a string
@@ -41349,7 +41787,7 @@
var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
var childrenNameType = getLiteralType(childrenPropName);
var childrenTargetType = getIndexedAccessType(target, childrenNameType);
- var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyWhiteSpaces; });
+ var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
if (!ts.length(validChildren)) {
return result;
}
@@ -41437,7 +41875,7 @@
return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation);
}
// recreate a tuple from the elements, if possible
- var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true);
+ var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
if (isTupleLikeType(tupleizedType)) {
return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation);
}
@@ -41503,6 +41941,14 @@
/*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */;
}
/**
+ * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
+ */
+ function isAnySignature(s) {
+ return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
+ s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
+ isTypeAny(getReturnTypeOfSignature(s));
+ }
+ /**
* See signatureRelatedTo, compareSignaturesIdentical
*/
function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) {
@@ -41510,13 +41956,16 @@
if (source === target) {
return -1 /* True */;
}
+ if (isAnySignature(target)) {
+ return -1 /* True */;
+ }
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);
+ source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
}
var sourceCount = getParameterCount(source);
var sourceRestType = getNonArrayRestType(source);
@@ -41587,7 +42036,7 @@
if (targetTypePredicate) {
var sourceTypePredicate = getTypePredicateOfSignature(source);
if (sourceTypePredicate) {
- result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217
+ result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
}
else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
if (reportErrors) {
@@ -41606,7 +42055,7 @@
}
return result;
}
- function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) {
+ function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
if (source.kind !== target.kind) {
if (reportErrors) {
errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
@@ -41615,12 +42064,9 @@
return 0 /* False */;
}
if (source.kind === 1 /* Identifier */) {
- var targetPredicate = target;
- var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0);
- var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0);
- if (sourceIndex !== targetIndex) {
+ if (source.parameterIndex !== target.parameterIndex) {
if (reportErrors) {
- errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName);
+ errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
}
return 0 /* False */;
@@ -41821,7 +42267,7 @@
}
var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
if (relatedInfo) {
- addRelatedInfo.apply(void 0, [diag].concat(relatedInfo));
+ ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInfo));
}
if (errorOutputContainer) {
errorOutputContainer.error = diag;
@@ -42428,8 +42874,8 @@
if (source.root.isDistributive === target.root.isDistributive) {
if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
- if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
- if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
+ if (result_3 &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) {
+ if (result_3 &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) {
return result_3;
}
}
@@ -42444,6 +42890,7 @@
}
var result;
var originalErrorInfo;
+ var varianceCheckFailed = false;
var saveErrorInfo = errorInfo;
// We limit alias variance probing to only object and conditional types since their alias behavior
// is more predictable than other, interned types, which may or may not have an alias depending on
@@ -42452,11 +42899,10 @@
source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
!(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
var variances = getAliasVariances(source.aliasSymbol);
- if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) {
- return result;
+ var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances);
+ if (varianceResult !== undefined) {
+ return varianceResult;
}
- originalErrorInfo = errorInfo;
- errorInfo = saveErrorInfo;
}
if (target.flags & 262144 /* TypeParameter */) {
// A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q].
@@ -42513,9 +42959,18 @@
template.indexType === getTypeParameterFromMappedType(target)) {
return -1 /* True */;
}
+ if (!isGenericMappedType(source)) {
+ var targetConstraint = getConstraintTypeFromMappedType(target);
+ var sourceKeys_1 = getIndexType(source);
+ var hasOptionalUnionKeys = modifiers & 4 /* IncludeOptional */ && targetConstraint.flags & 1048576 /* Union */;
+ var filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, function (t) { return !!isRelatedTo(t, sourceKeys_1); }) : undefined;
// A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X.
- if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) {
- var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target));
+ // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X.
+ if (hasOptionalUnionKeys
+ ? !(filteredByApplicability.flags & 131072 /* Never */)
+ : isRelatedTo(targetConstraint, sourceKeys_1)) {
+ var indexingType = hasOptionalUnionKeys ? filteredByApplicability : getTypeParameterFromMappedType(target);
+ var indexedAccessType = getIndexedAccessType(source, indexingType);
var templateType = getTemplateTypeFromMappedType(target);
if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
return result;
@@ -42525,6 +42980,7 @@
errorInfo = saveErrorInfo;
}
}
+ }
if (source.flags & 8650752 /* TypeVariable */) {
if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
// A type S[K] is related to a type T[J] if S is related to T and K is related to J.
@@ -42568,8 +43024,8 @@
// and Y1 is related to Y2.
if (isTypeIdenticalTo(source.extendsType, target.extendsType) &&
(isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
- if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) {
- result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
+ if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) {
+ result &= isRelatedTo(source.falseType, target.falseType, reportErrors);
}
if (result) {
errorInfo = saveErrorInfo;
@@ -42618,36 +43074,19 @@
// type references (which are intended by be compared structurally). Obtain the variance
// information for the type parameters and relate the type arguments accordingly.
var variances = getVariances(source.target);
- if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) {
- return result;
- }
- // The type arguments did not relate appropriately, but it may be because we have no variance
- // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
- // arguments). It might also be the case that the target type has a 'void' type argument for
- // a covariant type parameter that is only used in return positions within the generic type
- // (in which case any type argument is permitted on the source side). In those cases we proceed
- // with a structural comparison. Otherwise, we know for certain the instantiations aren't
- // related and we can return here.
- if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) {
- // In some cases generic types that are covariant in regular type checking mode become
- // invariant in --strictFunctionTypes mode because one or more type parameters are used in
- // both co- and contravariant positions. In order to make it easier to diagnose *why* such
- // types are invariant, if any of the type parameters are invariant we reset the reported
- // errors and instead force a structural comparison (which will include elaborations that
- // reveal the reason).
- if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) {
- return 0 /* False */;
- }
- // We remember the original error information so we can restore it in case the structural
- // comparison unexpectedly succeeds. This can happen when the structural comparison result
- // is a Ternary.Maybe for example caused by the recursion depth limiter.
- originalErrorInfo = errorInfo;
- errorInfo = saveErrorInfo;
+ var varianceResult = relateVariances(source.typeArguments, target.typeArguments, variances);
+ if (varianceResult !== undefined) {
+ return varianceResult;
}
}
- else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) {
+ else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
}
+ // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
+ // and not `{} <- fresh({}) <- {[idx: string]: any}`
+ else if (relation === subtypeRelation && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
+ return 0 /* False */;
+ }
// Even if relationship doesn't hold for unions, intersections, or generic type references,
// it may hold in a structural comparison.
// In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
@@ -42669,17 +43108,57 @@
}
}
}
- if (result) {
- if (!originalErrorInfo) {
- errorInfo = saveErrorInfo;
+ if (varianceCheckFailed && result) {
+ errorInfo = originalErrorInfo || errorInfo || saveErrorInfo; // Use variance error (there is no structural one) and return false
+ }
+ else if (result) {
return result;
}
- errorInfo = originalErrorInfo;
}
}
+ return 0 /* False */;
+ function isNonGeneric(type) {
+ // If we're already in identity relationship checking, we should use `isRelatedTo`
+ // to catch the `Maybe` from an excessively deep type (which we then assume means
+ // that the type could possibly contain a generic)
+ if (relation === identityRelation) {
+ return isRelatedTo(type, getPermissiveInstantiation(type)) === -1 /* True */;
+ }
+ return isTypeIdenticalTo(type, getPermissiveInstantiation(type));
+ }
+ function relateVariances(sourceTypeArguments, targetTypeArguments, variances) {
+ if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors)) {
+ return result;
}
+ var allowStructuralFallback = (targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances)) || isNonGeneric(source) || isNonGeneric(target);
+ varianceCheckFailed = !allowStructuralFallback;
+ // The type arguments did not relate appropriately, but it may be because we have no variance
+ // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
+ // arguments). It might also be the case that the target type has a 'void' type argument for
+ // a covariant type parameter that is only used in return positions within the generic type
+ // (in which case any type argument is permitted on the source side). In those cases we proceed
+ // with a structural comparison. Otherwise, we know for certain the instantiations aren't
+ // related and we can return here.
+ if (variances !== ts.emptyArray && !allowStructuralFallback) {
+ // In some cases generic types that are covariant in regular type checking mode become
+ // invariant in --strictFunctionTypes mode because one or more type parameters are used in
+ // both co- and contravariant positions. In order to make it easier to diagnose *why* such
+ // types are invariant, if any of the type parameters are invariant we reset the reported
+ // errors and instead force a structural comparison (which will include elaborations that
+ // reveal the reason).
+ // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
+ // we can return `False` early here to skip calculating the structural error message we don't need.
+ if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) {
return 0 /* False */;
}
+ // We remember the original error information so we can restore it in case the structural
+ // comparison unexpectedly succeeds. This can happen when the structural comparison result
+ // is a Ternary.Maybe for example caused by the recursion depth limiter.
+ originalErrorInfo = errorInfo;
+ errorInfo = saveErrorInfo;
+ }
+ }
+ }
// A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
// related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
// that S and T are contra-variant whereas X and Y are co-variant.
@@ -43158,20 +43637,17 @@
return variances;
}
function getVariances(type) {
- if (!strictFunctionTypes) {
- return ts.emptyArray;
- }
- if (type === globalArrayType || type === globalReadonlyArrayType) {
- // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters)
+ // Arrays and tuples are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters)
+ if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
return ts.emptyArray;
}
return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
}
// Return true if the given type reference has a 'void' type argument for a covariant type parameter.
// See comment at call in recursiveTypeRelatedTo for when this case matters.
- function hasCovariantVoidArgument(type, variances) {
+ function hasCovariantVoidArgument(typeArguments, variances) {
for (var i = 0; i < variances.length; i++) {
- if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) {
+ if (variances[i] === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
return true;
}
}
@@ -43400,8 +43876,8 @@
}
function literalTypesWithSameBaseType(types) {
var commonBaseType;
- for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
- var t = types_8[_i];
+ for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
+ var t = types_9[_i];
var baseType = getBaseTypeOfLiteralType(t);
if (!commonBaseType) {
commonBaseType = baseType;
@@ -43434,7 +43910,7 @@
return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
}
function isArrayType(type) {
- return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType;
+ return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
}
function isReadonlyArrayType(type) {
return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
@@ -43445,8 +43921,7 @@
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<any>
- return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) ||
- !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
+ return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
}
function isEmptyArrayLiteralType(type) {
var elementType = isArrayType(type) ? type.typeArguments[0] : undefined;
@@ -43531,8 +44006,8 @@
}
function getFalsyFlagsOfTypes(types) {
var result = 0;
- for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
- var t = types_9[_i];
+ for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
+ var t = types_10[_i];
result |= getFalsyFlags(t);
}
return result;
@@ -43646,7 +44121,7 @@
var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
regularNew.flags = resolved.flags;
- regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */);
+ regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
type.regularType = regularNew;
return regularNew;
}
@@ -43725,14 +44200,14 @@
var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
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
+ result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening
return result;
}
function getWidenedType(type) {
return getWidenedTypeWithContext(type, /*context*/ undefined);
}
function getWidenedTypeWithContext(type, context) {
- if (type.flags & 402653184 /* RequiresWidening */) {
+ if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) {
if (type.flags & 98304 /* Nullable */) {
return anyType;
}
@@ -43769,7 +44244,7 @@
*/
function reportWideningErrorsInType(type) {
var errorReported = false;
- if (type.flags & 134217728 /* ContainsWideningType */) {
+ if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) {
if (type.flags & 1048576 /* Union */) {
if (ts.some(type.types, isEmptyObjectType)) {
errorReported = true;
@@ -43795,7 +44270,7 @@
for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
var p = _e[_d];
var t = getTypeOfSymbol(p);
- if (t.flags & 134217728 /* ContainsWideningType */) {
+ if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) {
if (!reportWideningErrorsInType(t)) {
error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
}
@@ -43841,7 +44316,7 @@
return;
}
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
return;
case 239 /* FunctionDeclaration */:
@@ -43868,14 +44343,14 @@
errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
}
function reportErrorsFromWidening(declaration, type) {
- if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) {
+ if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) {
// Report implicit any error within type if possible, otherwise report error on declaration
if (!reportWideningErrorsInType(type)) {
reportImplicitAny(declaration, type);
}
}
}
- function forEachMatchingParameterType(source, target, callback) {
+ function applyToParameterTypes(source, target, callback) {
var sourceCount = getParameterCount(source);
var targetCount = getParameterCount(target);
var sourceRestType = getEffectiveRestType(source);
@@ -43896,25 +44371,55 @@
callback(getRestTypeAtPosition(source, paramCount), targetRestType);
}
}
- function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) {
- var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo);
- var context = mapper;
- context.typeParameters = typeParameters;
- context.signature = signature;
- context.inferences = inferences;
- context.flags = flags;
- context.compareTypes = compareTypes || compareTypesAssignable;
+ function applyToReturnTypes(source, target, callback) {
+ var sourceTypePredicate = getTypePredicateOfSignature(source);
+ var targetTypePredicate = getTypePredicateOfSignature(target);
+ if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind &&
+ (sourceTypePredicate.kind === 0 /* This */ || sourceTypePredicate.parameterIndex === targetTypePredicate.parameterIndex)) {
+ callback(sourceTypePredicate.type, targetTypePredicate.type);
+ }
+ else {
+ callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
+ }
+ }
+ function createInferenceContext(typeParameters, signature, flags, compareTypes) {
+ return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
+ }
+ function cloneInferenceContext(context, extraFlags) {
+ if (extraFlags === void 0) { extraFlags = 0; }
+ return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
+ }
+ function cloneInferredPartOfContext(context) {
+ var inferences = ts.filter(context.inferences, hasInferenceCandidates);
+ return inferences.length ?
+ createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
+ undefined;
+ }
+ function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
+ var context = {
+ inferences: inferences,
+ signature: signature,
+ flags: flags,
+ compareTypes: compareTypes,
+ mapper: function (t) { return mapToInferredType(context, t, /*fix*/ true); },
+ nonFixingMapper: function (t) { return mapToInferredType(context, t, /*fix*/ false); },
+ };
return context;
- function mapper(t) {
+ }
+ function mapToInferredType(context, t, fix) {
+ var inferences = context.inferences;
for (var i = 0; i < inferences.length; i++) {
- if (t === inferences[i].typeParameter) {
- inferences[i].isFixed = true;
+ var inference = inferences[i];
+ if (t === inference.typeParameter) {
+ if (fix && !inference.isFixed) {
+ inference.isFixed = true;
+ inference.inferredType = undefined;
+ }
return getInferredType(context, i);
}
}
return t;
}
- }
function createInferenceInfo(typeParameter) {
return {
typeParameter: typeParameter,
@@ -43937,6 +44442,9 @@
isFixed: inference.isFixed
};
}
+ function getMapperFromContext(context) {
+ return context && context.mapper;
+ }
// Return true if the given type could possibly reference a type parameter for which
// we perform type inference (i.e. a type parameter of a generic function). We cache
// results for union and intersection types for performance reasons.
@@ -43993,31 +44501,21 @@
return type;
}
function createReverseMappedType(source, target, constraint) {
- var properties = getPropertiesOfType(source);
- if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) {
- return undefined;
- }
// If any property contains context sensitive functions that have been skipped, the source type
// is incomplete and we can't infer a meaningful input type.
- for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
- var prop = properties_3[_i];
- if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) {
+ if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || getPropertiesOfType(source).length === 0 && !getIndexInfoOfType(source, 0 /* String */)) {
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, constraint));
- }
- if (isReadonlyArrayType(source)) {
- return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint));
+ return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint), isReadonlyArrayType(source));
}
if (isTupleType(source)) {
var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); });
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);
+ return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, 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.
@@ -44038,16 +44536,16 @@
return getTypeFromInference(inference);
}
function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
- var properties, _i, properties_4, targetProp, sourceProp, targetType, sourceType;
+ var properties, _i, properties_3, targetProp, sourceProp, targetType, sourceType;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target);
- _i = 0, properties_4 = properties;
+ _i = 0, properties_3 = properties;
_a.label = 1;
case 1:
- if (!(_i < properties_4.length)) return [3 /*break*/, 6];
- targetProp = properties_4[_i];
+ if (!(_i < properties_3.length)) return [3 /*break*/, 6];
+ targetProp = properties_3[_i];
if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 5];
sourceProp = getPropertyOfType(source, targetProp.escapedName);
if (!!sourceProp) return [3 /*break*/, 3];
@@ -44091,11 +44589,11 @@
inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
emptyObjectType;
}
- function inferTypes(inferences, originalSource, originalTarget, priority) {
+ function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
if (priority === void 0) { priority = 0; }
+ if (contravariant === void 0) { contravariant = false; }
var symbolStack;
var visited;
- var contravariant = false;
var bivariant = false;
var propagationType;
var allowComplexConstraintInference = true;
@@ -44171,7 +44669,7 @@
// not contain anyFunctionType when we come back to this argument for its second round
// of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
// when constructing types from type parameters that had no inference candidates).
- if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) {
+ if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) {
return;
}
var inference = getInferenceInfoForType(target);
@@ -44180,6 +44678,7 @@
if (inference.priority === undefined || priority < inference.priority) {
inference.candidates = undefined;
inference.contraCandidates = undefined;
+ inference.topLevel = true;
inference.priority = priority;
}
if (priority === inference.priority) {
@@ -44187,14 +44686,19 @@
// We make contravariant inferences only if we are in a pure contravariant position,
// i.e. only if we have not descended into a bivariant position.
if (contravariant && !bivariant) {
- inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate);
+ if (!ts.contains(inference.contraCandidates, candidate)) {
+ inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
+ inference.inferredType = undefined;
}
- else {
- inference.candidates = ts.appendIfUnique(inference.candidates, candidate);
+ }
+ else if (!ts.contains(inference.candidates, candidate)) {
+ inference.candidates = ts.append(inference.candidates, candidate);
+ inference.inferredType = undefined;
}
}
- if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) {
+ if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
inference.topLevel = false;
+ inference.inferredType = undefined;
}
}
return;
@@ -44218,6 +44722,9 @@
}
}
}
+ else if (target.flags & 33554432 /* Substitution */) {
+ inferFromTypes(source, target.typeVariable);
+ }
if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) {
// If source and target are references to the same generic type, infer from type arguments
var sourceTypes = source.typeArguments || ts.emptyArray;
@@ -44254,42 +44761,48 @@
else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) {
inferFromTypes(source.checkType, target.checkType);
inferFromTypes(source.extendsType, target.extendsType);
- inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
- inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
+ inferFromTypes(source.trueType, target.trueType);
+ inferFromTypes(source.falseType, target.falseType);
}
- else if (target.flags & 16777216 /* Conditional */) {
- inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]));
+ else if (target.flags & 16777216 /* Conditional */ && !contravariant) {
+ inferFromTypes(source, target.trueType);
+ inferFromTypes(source, target.falseType);
}
else if (target.flags & 3145728 /* UnionOrIntersection */) {
- var targetTypes = target.types;
+ // We infer from types that are not naked type variables first so that inferences we
+ // make from nested naked type variables and given slightly higher priority by virtue
+ // of being first in the candidates array.
var typeVariableCount = 0;
- var typeVariable = void 0;
- // First infer to each type in union or intersection that isn't a type variable
- for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) {
- var t = targetTypes_3[_d];
+ for (var _d = 0, _e = target.types; _d < _e.length; _d++) {
+ var t = _e[_d];
if (getInferenceInfoForType(t)) {
- typeVariable = t;
typeVariableCount++;
}
else {
inferFromTypes(source, t);
}
}
- // Next, if target containings a single naked type variable, make a secondary inference to that type
- // variable. This gives meaningful results for union types in co-variant positions and intersection
- // types in contra-variant positions (such as callback parameters).
- if (typeVariableCount === 1) {
+ // Inferences directly to naked type variables are given lower priority as they are
+ // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
+ // we want to infer string for T, not Promise<string> | string. For intersection types
+ // we only infer to single naked type variables.
+ if (target.flags & 1048576 /* Union */ ? typeVariableCount !== 0 : typeVariableCount === 1) {
var savePriority = priority;
priority |= 1 /* NakedTypeVariable */;
- inferFromTypes(source, typeVariable);
+ for (var _f = 0, _g = target.types; _f < _g.length; _f++) {
+ var t = _g[_f];
+ if (getInferenceInfoForType(t)) {
+ inferFromTypes(source, t);
+ }
+ }
priority = savePriority;
}
}
else if (source.flags & 1048576 /* Union */) {
// Source is a union or intersection type, infer from each constituent type
var sourceTypes = source.types;
- for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) {
- var sourceType = sourceTypes_3[_e];
+ for (var _h = 0, sourceTypes_3 = sourceTypes; _h < sourceTypes_3.length; _h++) {
+ var sourceType = sourceTypes_3[_h];
inferFromTypes(sourceType, target);
}
}
@@ -44305,7 +44818,7 @@
// that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
// here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
// (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
- // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just
+ // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
// remove this `allowComplexConstraintInference` flag.
allowComplexConstraintInference = false;
return inferFromTypes(apparentSource, target);
@@ -44367,12 +44880,12 @@
}
return undefined;
}
- function inferFromMappedTypeConstraint(source, target, constraintType) {
+ function inferToMappedType(source, target, constraintType) {
if (constraintType.flags & 1048576 /* Union */) {
var result = false;
for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
var type = _a[_i];
- result = inferFromMappedTypeConstraint(source, target, type) || result;
+ result = inferToMappedType(source, target, type) || result;
}
return result;
}
@@ -44394,12 +44907,22 @@
return true;
}
if (constraintType.flags & 262144 /* TypeParameter */) {
- // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type
- // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X.
+ // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
+ // parameter. First infer from 'keyof S' to K.
var savePriority = priority;
priority |= 4 /* MappedTypeConstraint */;
inferFromTypes(getIndexType(source), constraintType);
priority = savePriority;
+ // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
+ // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
+ // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
+ // Pick<T, K>.
+ var extendedConstraint = getConstraintOfType(constraintType);
+ if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
+ return true;
+ }
+ // If no inferences can be made to K's constraint, infer from a union of the property types
+ // in the source to the template type X.
var valueTypes = ts.compact([
getIndexTypeOfType(source, 0 /* String */),
getIndexTypeOfType(source, 1 /* Number */)
@@ -44418,7 +44941,7 @@
}
if (ts.getObjectFlags(target) & 32 /* Mapped */) {
var constraintType = getConstraintTypeFromMappedType(target);
- if (inferFromMappedTypeConstraint(source, target, constraintType)) {
+ if (inferToMappedType(source, target, constraintType)) {
return;
}
}
@@ -44431,11 +44954,11 @@
}
}
function inferFromProperties(source, target) {
- if (isTupleType(source)) {
+ if (isArrayType(source) || isTupleType(source)) {
if (isTupleType(target)) {
- var sourceLength = getLengthOfTupleType(source);
+ var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0;
var targetLength = getLengthOfTupleType(target);
- var sourceRestType = getRestTypeOfTupleType(source);
+ var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source);
var targetRestType = getRestTypeOfTupleType(target);
var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
for (var i = 0; i < fixedLength; i++) {
@@ -44458,8 +44981,8 @@
}
}
var properties = getPropertiesOfObjectType(target);
- for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
- var targetProp = properties_5[_i];
+ for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) {
+ var targetProp = properties_4[_i];
var sourceProp = getPropertyOfType(source, targetProp.escapedName);
if (sourceProp) {
inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
@@ -44472,7 +44995,7 @@
var sourceLen = sourceSignatures.length;
var targetLen = targetSignatures.length;
var len = sourceLen < targetLen ? sourceLen : targetLen;
- var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */);
+ var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */);
for (var i = 0; i < len; i++) {
inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters);
}
@@ -44483,17 +45006,10 @@
var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
// Once we descend into a bivariant signature we remain bivariant for all nested inferences
bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */;
- forEachMatchingParameterType(source, target, inferFromContravariantTypes);
+ applyToParameterTypes(source, target, inferFromContravariantTypes);
bivariant = saveBivariant;
}
- var sourceTypePredicate = getTypePredicateOfSignature(source);
- var targetTypePredicate = getTypePredicateOfSignature(target);
- if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) {
- inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type);
- }
- else {
- inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
- }
+ applyToReturnTypes(source, target, inferFromTypes);
}
function inferFromIndexTypes(source, target) {
var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
@@ -44516,8 +45032,8 @@
}
}
function typeIdenticalToSomeType(type, types) {
- for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
- var t = types_10[_i];
+ for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
+ var t = types_11[_i];
if (isTypeIdenticalTo(t, type)) {
return true;
}
@@ -44610,7 +45126,7 @@
if (defaultType) {
// Instantiate the default type. Any forward reference to a type
// parameter should be instantiated to the empty object type.
- inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
}
else {
inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
@@ -44623,7 +45139,7 @@
inference.inferredType = inferredType;
var constraint = getConstraintOfTypeParameter(inference.typeParameter);
if (constraint) {
- var instantiatedConstraint = instantiateType(constraint, context);
+ var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
inference.inferredType = inferredType = instantiatedConstraint;
}
@@ -44648,17 +45164,23 @@
case "console":
return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
case "$":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
case "describe":
case "suite":
case "it":
case "test":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha;
case "process":
case "require":
case "Buffer":
case "module":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
case "Map":
case "Set":
case "Promise":
@@ -44794,9 +45316,8 @@
}
return false;
}
- function hasNarrowableDeclaredType(expr) {
- var type = getDeclaredTypeOfReference(expr);
- return !!(type && type.flags & 1048576 /* Union */);
+ function isSyntheticThisPropertyAccess(expr) {
+ return ts.isAccessExpression(expr) && expr.expression.kind === 100 /* ThisKeyword */ && !!(expr.expression.flags & 8 /* Synthesized */);
}
function findDiscriminantProperties(sourceProperties, target) {
var result;
@@ -44873,8 +45394,8 @@
}
function getTypeFactsOfTypes(types) {
var result = 0 /* None */;
- for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
- var t = types_11[_i];
+ for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
+ var t = types_12[_i];
result |= getTypeFacts(t);
}
return result;
@@ -45154,7 +45675,7 @@
if (type.flags & 1048576 /* Union */) {
var types = type.types;
var filtered = ts.filter(types, f);
- return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly);
+ return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
}
return f(type) ? type : neverType;
}
@@ -45168,8 +45689,8 @@
var types = type.types;
var mappedType;
var mappedTypes;
- for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
- var current = types_12[_i];
+ for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
+ var current = types_13[_i];
var t = mapper(current);
if (t) {
if (!mappedType) {
@@ -45251,8 +45772,8 @@
}
function isEvolvingArrayTypeList(types) {
var hasEvolvingArrayType = false;
- for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
- var t = types_13[_i];
+ for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
+ var t = types_14[_i];
if (!(t.flags & 131072 /* Never */)) {
if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
return false;
@@ -45750,6 +46271,15 @@
assumeTrue = !assumeTrue;
}
var valueType = getTypeOfExpression(value);
+ if ((type.flags & 2 /* Unknown */) && (operator === 35 /* EqualsEqualsEqualsToken */) && assumeTrue) {
+ if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
+ return valueType;
+ }
+ if (valueType.flags & 524288 /* Object */) {
+ return nonPrimitiveType;
+ }
+ return type;
+ }
if (valueType.flags & 98304 /* Nullable */) {
if (!strictNullChecks) {
return type;
@@ -45779,9 +46309,9 @@
// We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands
var target = getReferenceCandidate(typeOfExpr.expression);
if (!isMatchingReference(reference, target)) {
- // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a
- // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type.
- if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) {
+ // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the
+ // narrowed type of 'y' to its declared type.
+ if (containsMatchingReference(reference, target)) {
return declaredType;
}
return type;
@@ -45822,13 +46352,37 @@
}
}
function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
- // We only narrow if all case expressions specify values with unit types
+ // We only narrow if all case expressions specify
+ // values with unit types, except for the case where
+ // `type` is unknown. In this instance we map object
+ // types to the nonPrimitive type and narrow with that.
var switchTypes = getSwitchClauseTypes(switchStatement);
if (!switchTypes.length) {
return type;
}
var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
+ if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
+ var groundClauseTypes = void 0;
+ for (var i = 0; i < clauseTypes.length; i += 1) {
+ var t = clauseTypes[i];
+ if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
+ if (groundClauseTypes !== undefined) {
+ groundClauseTypes.push(t);
+ }
+ }
+ else if (t.flags & 524288 /* Object */) {
+ if (groundClauseTypes === undefined) {
+ groundClauseTypes = clauseTypes.slice(0, i);
+ }
+ groundClauseTypes.push(nonPrimitiveType);
+ }
+ else {
+ return type;
+ }
+ }
+ return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
+ }
var discriminantType = getUnionType(clauseTypes);
var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
@@ -45929,9 +46483,14 @@
function narrowTypeByInstanceof(type, expr, assumeTrue) {
var left = getReferenceCandidate(expr.left);
if (!isMatchingReference(reference, left)) {
- // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an
- // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type.
- if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) {
+ // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the
+ // narrowed type of 'y' to its declared type. We do this because preceding 'x.y'
+ // references might reference a different 'y' property. However, we make an exception
+ // for property accesses where x is a synthetic 'this' expression, indicating that we
+ // were called from isPropertyInitializedInConstructor. Without this exception,
+ // initializations of 'this' properties that occur before a 'this instanceof XXX'
+ // check would not be considered.
+ if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) {
return declaredType;
}
return type;
@@ -45998,7 +46557,7 @@
return type;
}
if (ts.isIdentifierTypePredicate(predicate)) {
- var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)];
+ var predicateArgument = callExpression.arguments[predicate.parameterIndex];
if (predicateArgument) {
if (isMatchingReference(reference, predicateArgument)) {
return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
@@ -46075,7 +46634,7 @@
return ts.findAncestor(node.parent, function (node) {
return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
node.kind === 245 /* ModuleBlock */ ||
- node.kind === 279 /* SourceFile */ ||
+ node.kind === 284 /* SourceFile */ ||
node.kind === 154 /* PropertyDeclaration */;
});
}
@@ -46196,7 +46755,7 @@
// 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 !== 279 /* SourceFile */) {
+ while (container.kind !== 284 /* SourceFile */) {
if (container.parent === declaration) {
if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
@@ -46302,6 +46861,7 @@
function checkNestedBlockScopedBinding(node, symbol) {
if (languageVersion >= 2 /* ES2015 */ ||
(symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
+ ts.isSourceFile(symbol.valueDeclaration) ||
symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) {
return;
}
@@ -46489,22 +47049,27 @@
if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
captureLexicalThis(node, container);
}
- var type = tryGetThisTypeAt(node, container);
- if (!type && noImplicitThis) {
+ var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
+ if (noImplicitThis) {
+ var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
+ if (type === globalThisType_1 && capturedByArrowFunction) {
+ error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
+ }
+ else if (!type) {
// With noImplicitThis, functions may not reference 'this' if it has type 'any'
- var diag = error(node, capturedByArrowFunction && container.kind === 279 /* 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);
+ var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
if (!ts.isSourceFile(container)) {
var outsideThis = tryGetThisTypeAt(container);
- if (outsideThis) {
- addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
+ if (outsideThis && outsideThis !== globalThisType_1) {
+ ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
+ }
}
}
}
return type || anyType;
}
- function tryGetThisTypeAt(node, container) {
+ function tryGetThisTypeAt(node, includeGlobalThis, container) {
+ if (includeGlobalThis === void 0) { includeGlobalThis = true; }
if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
var isInJS = ts.isInJSFile(node);
if (ts.isFunctionLike(container) &&
@@ -46549,6 +47114,16 @@
return getFlowTypeOfReference(node, type);
}
}
+ if (ts.isSourceFile(container)) {
+ // look up in the source file's locals or exports
+ if (container.commonJsModuleIndicator) {
+ var fileSymbol = getSymbolOfNode(container);
+ return fileSymbol && getTypeOfSymbol(fileSymbol);
+ }
+ else if (includeGlobalThis) {
+ return getTypeOfSymbol(globalThisSymbol);
+ }
+ }
}
function getClassNameFromPrototypeMethod(container) {
// Check if it's the RHS of a x.prototype.y = function [name]() { .... }
@@ -46604,7 +47179,7 @@
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 294 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -46618,7 +47193,7 @@
}
}
function isInConstructorArgumentInitializer(node, constructorDecl) {
- return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; });
+ return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 151 /* Parameter */ && n.parent === constructorDecl; });
}
function checkSuperExpression(node) {
var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node;
@@ -46843,7 +47418,7 @@
while (type) {
var thisType = getThisTypeFromContextualType(type);
if (thisType) {
- return instantiateType(thisType, getContextualMapper(containingLiteral));
+ return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
}
if (literal.parent.kind !== 275 /* PropertyAssignment */) {
break;
@@ -47138,7 +47713,15 @@
}
function getTypeOfPropertyOfContextualType(type, name) {
return mapType(type, function (t) {
- if (t.flags & 3670016 /* StructuredType */) {
+ if (isGenericMappedType(t)) {
+ var constraint = getConstraintTypeFromMappedType(t);
+ var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
+ var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
+ if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
+ return substituteIndexedMappedType(t, propertyNameType);
+ }
+ }
+ else if (t.flags & 3670016 /* StructuredType */) {
var prop = getPropertyOfType(t, name);
if (prop) {
return getTypeOfSymbol(prop);
@@ -47274,18 +47857,46 @@
// Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
// be "pushed" onto a node using the contextualType property.
function getApparentTypeOfContextualType(node) {
- var contextualType = getContextualType(node);
- contextualType = contextualType && mapType(contextualType, getApparentType);
- if (contextualType && contextualType.flags & 1048576 /* Union */) {
+ var contextualType = instantiateContextualType(getContextualType(node), node);
+ if (contextualType) {
+ var apparentType = mapType(contextualType, getApparentType, /*noReductions*/ true);
+ if (apparentType.flags & 1048576 /* Union */) {
if (ts.isObjectLiteralExpression(node)) {
- return discriminateContextualTypeByObjectMembers(node, contextualType);
+ return discriminateContextualTypeByObjectMembers(node, apparentType);
}
else if (ts.isJsxAttributes(node)) {
- return discriminateContextualTypeByJSXAttributes(node, contextualType);
+ return discriminateContextualTypeByJSXAttributes(node, apparentType);
+ }
+ }
+ return apparentType;
+ }
+ }
+ // If the given contextual type contains instantiable types and if a mapper representing
+ // return type inferences is available, instantiate those types using that mapper.
+ function instantiateContextualType(contextualType, node) {
+ if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) {
+ var inferenceContext = getInferenceContext(node);
+ if (inferenceContext && inferenceContext.returnMapper) {
+ return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
}
}
return contextualType;
}
+ // This function is similar to instantiateType, except that (a) it only instantiates types that
+ // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
+ // no reductions on instantiated union types.
+ function instantiateInstantiableTypes(type, mapper) {
+ if (type.flags & 63176704 /* Instantiable */) {
+ return instantiateType(type, mapper);
+ }
+ if (type.flags & 1048576 /* Union */) {
+ return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
+ }
+ if (type.flags & 2097152 /* Intersection */) {
+ return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
+ }
+ return type;
+ }
/**
* Woah! Do you really want to use this function?
*
@@ -47331,7 +47942,7 @@
return getContextualTypeForArgument(parent, node);
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- return getTypeFromTypeNode(parent.type);
+ return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type);
case 204 /* BinaryExpression */:
return getContextualTypeForBinaryOperand(node);
case 275 /* PropertyAssignment */:
@@ -47365,9 +47976,9 @@
}
return undefined;
}
- function getContextualMapper(node) {
- var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; });
- return ancestor ? ancestor.contextualMapper : identityMapper;
+ function getInferenceContext(node) {
+ var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
+ return ancestor && ancestor.inferenceContext;
}
function getContextualJsxElementAttributesType(node) {
if (ts.isJsxOpeningElement(node) && node.parent.contextualType) {
@@ -47548,8 +48159,8 @@
}
var signatureList;
var types = type.types;
- for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
- var current = types_14[_i];
+ for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
+ var current = types_15[_i];
var signature = getContextualCallSignature(current, node);
if (signature) {
if (!signatureList) {
@@ -47567,12 +48178,7 @@
}
}
// Result is union of signatures collected (return type is union of return types of this signature set)
- var result;
- if (signatureList) {
- result = cloneSignature(signatureList[0]);
- result.unionSignatures = signatureList;
- }
- return result;
+ return signatureList && createUnionSignature(signatureList[0], signatureList);
}
function checkSpreadExpression(node, checkMode) {
if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
@@ -47592,6 +48198,7 @@
var elementTypes = [];
var inDestructuringPattern = ts.isAssignmentTarget(node);
var contextualType = getApparentTypeOfContextualType(node);
+ var inConstContext = isConstContext(node);
for (var index = 0; index < elementCount; index++) {
var e = elements[index];
if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) {
@@ -47634,21 +48241,24 @@
type.pattern = node;
return type;
}
- else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) {
+ else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, inConstContext)) {
return tupleResult;
}
else if (forceTuple) {
return createTupleType(elementTypes, minLength, hasRestElement);
}
}
- return getArrayLiteralType(elementTypes, 2 /* Subtype */);
+ return createArrayType(elementTypes.length ?
+ getUnionType(elementTypes, 2 /* Subtype */) :
+ strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext);
}
- function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) {
+ function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) {
if (elementCount === void 0) { elementCount = elementTypes.length; }
+ if (readonly === void 0) { readonly = false; }
// Infer a tuple type when the contextual type is or contains a tuple-like type
- if (contextualType && forEachType(contextualType, isTupleLikeType)) {
+ if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) {
var minLength = elementCount - (hasRestElement ? 1 : 0);
- var pattern = contextualType.pattern;
+ var pattern = contextualType && 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 (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) {
@@ -47666,15 +48276,9 @@
}
}
}
- return createTupleType(elementTypes, minLength, hasRestElement);
+ return createTupleType(elementTypes, minLength, hasRestElement, readonly);
}
}
- function getArrayLiteralType(elementTypes, unionReduction) {
- if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
- return createArrayType(elementTypes.length ?
- getUnionType(elementTypes, unionReduction) :
- strictNullChecks ? implicitNeverType : undefinedWideningType);
- }
function isNumericName(name) {
switch (name.kind) {
case 149 /* ComputedPropertyName */:
@@ -47737,15 +48341,15 @@
}
return links.resolvedType;
}
- function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) {
+ function getObjectLiteralIndexInfo(node, offset, properties, kind) {
var propTypes = [];
for (var i = 0; i < properties.length; i++) {
- if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) {
+ if (kind === 0 /* String */ || isNumericName(node.properties[i + offset].name)) {
propTypes.push(getTypeOfSymbol(properties[i]));
}
}
var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
- return createIndexInfo(unionType, /*isReadonly*/ false);
+ return createIndexInfo(unionType, isConstContext(node));
}
function getImmediateAliasedSymbol(symbol) {
ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
@@ -47765,14 +48369,15 @@
var propertiesTable;
var propertiesArray = [];
var spread = emptyObjectType;
- var propagatedFlags = 0;
var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */);
+ var inConstContext = isConstContext(node);
+ var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
var enumTag = ts.getJSDocEnumTag(node);
var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
- var typeFlags = 0;
+ var objectFlags = freshObjectLiteralFlag;
var patternWithComputedProperties = false;
var hasComputedStringProperty = false;
var hasComputedNumberProperty = false;
@@ -47799,11 +48404,11 @@
checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
}
}
- typeFlags |= type.flags;
+ objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */;
var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
var prop = nameType ?
- createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), 2048 /* Late */) :
- createSymbol(4 /* Property */ | member.flags, member.escapedName);
+ createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 2048 /* Late */) :
+ createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
if (nameType) {
prop.nameType = nameType;
}
@@ -47841,19 +48446,18 @@
checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
}
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
propertiesArray = [];
propertiesTable = ts.createSymbolTable();
hasComputedStringProperty = false;
hasComputedNumberProperty = false;
- typeFlags = 0;
}
var type = checkExpression(memberDecl.expression);
if (!isValidSpreadType(type)) {
error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
return errorType;
}
- spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
offset = i + 1;
continue;
}
@@ -47900,17 +48504,16 @@
}
if (spread !== emptyObjectType) {
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
}
return spread;
}
return createObjectLiteralType();
function createObjectLiteralType() {
- var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined;
- var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined;
+ var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
+ var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
- result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */;
- result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag;
+ result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
if (isJSObjectLiteral) {
result.objectFlags |= 16384 /* JSLiteral */;
}
@@ -47920,7 +48523,6 @@
if (inDestructuringPattern) {
result.pattern = node;
}
- propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */;
return result;
}
}
@@ -47996,7 +48598,6 @@
var hasSpreadAnyType = false;
var typeToIntersect;
var explicitlySpecifyChildrenAttribute = false;
- var typeFlags = 0;
var objectFlags = 4096 /* JsxAttributes */;
var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
@@ -48004,7 +48605,7 @@
var member = attributeDecl.symbol;
if (ts.isJsxAttribute(attributeDecl)) {
var exprType = checkJsxAttribute(attributeDecl, checkMode);
- typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */;
+ objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */;
var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
attributeSymbol.declarations = member.declarations;
attributeSymbol.parent = member.parent;
@@ -48021,7 +48622,7 @@
else {
ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */);
if (attributesTable.size > 0) {
- spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
attributesTable = ts.createSymbolTable();
}
var exprType = checkExpressionCached(attributeDecl.expression, checkMode);
@@ -48029,7 +48630,7 @@
hasSpreadAnyType = true;
}
if (isValidSpreadType(exprType)) {
- spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
}
else {
typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
@@ -48038,7 +48639,7 @@
}
if (!hasSpreadAnyType) {
if (attributesTable.size > 0) {
- spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
}
}
// Handle children attribute
@@ -48066,7 +48667,7 @@
childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
var childPropMap = ts.createSymbolTable();
childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
- spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
}
}
if (hasSpreadAnyType) {
@@ -48084,8 +48685,7 @@
function createJsxAttributesType() {
objectFlags |= freshObjectLiteralFlag;
var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
- result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags;
- result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags;
+ result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
return result;
}
}
@@ -48096,7 +48696,7 @@
// In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
// because then type of children property will have constituent of string type.
if (child.kind === 11 /* JsxText */) {
- if (!child.containsOnlyWhiteSpaces) {
+ if (!child.containsOnlyTriviaWhiteSpaces) {
childrenTypes.push(stringType);
}
}
@@ -48167,7 +48767,7 @@
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 */);
+ var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
if (candidate) {
if (links) {
links.jsxNamespace = candidate;
@@ -48372,7 +48972,7 @@
// Mark local symbol as referenced here because it might not have been marked
// if jsx emit was not react as there wont be error being emitted
reactSym.isReferenced = 67108863 /* All */;
- // If react symbol is alias, mark it as refereced
+ // If react symbol is alias, mark it as referenced
if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) {
markAliasSymbolAsReferenced(reactSym);
}
@@ -48610,6 +49210,15 @@
if (isJSLiteralType(leftType)) {
return anyType;
}
+ if (leftType.symbol === globalThisSymbol) {
+ if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
+ error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
+ }
+ else if (noImplicitAny) {
+ error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
+ }
+ return anyType;
+ }
if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType);
}
@@ -48688,7 +49297,7 @@
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));
+ ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
}
}
function isInPropertyInitializer(node) {
@@ -48697,7 +49306,19 @@
case 154 /* PropertyDeclaration */:
return true;
case 275 /* PropertyAssignment */:
- // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`.
+ case 156 /* MethodDeclaration */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
+ case 277 /* SpreadAssignment */:
+ case 149 /* ComputedPropertyName */:
+ case 216 /* TemplateSpan */:
+ case 270 /* JsxExpression */:
+ case 267 /* JsxAttribute */:
+ case 268 /* JsxAttributes */:
+ case 269 /* JsxSpreadAttribute */:
+ case 262 /* JsxOpeningElement */:
+ case 211 /* ExpressionWithTypeArguments */:
+ case 273 /* HeritageClause */:
return false;
default:
return ts.isExpressionNode(node) ? false : "quit";
@@ -48765,7 +49386,7 @@
}
var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
if (relatedInfo) {
- addRelatedInfo(resultDiagnostic, relatedInfo);
+ ts.addRelatedInfo(resultDiagnostic, relatedInfo);
}
diagnostics.add(resultDiagnostic);
}
@@ -49164,38 +49785,34 @@
return undefined;
}
// 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) {
+ function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
- var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature;
- forEachMatchingParameterType(sourceSignature, signature, function (source, target) {
+ // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
+ // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
+ // for T but leave it possible to later infer '[any]' back to A.
+ var restType = getEffectiveRestType(contextualSignature);
+ var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
+ var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
+ applyToParameterTypes(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, source, target);
});
- if (!contextualMapper) {
- inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */);
+ if (!inferenceContext) {
+ applyToReturnTypes(contextualSignature, signature, function (source, target) {
+ inferTypes(context.inferences, source, target, 8 /* ReturnType */);
+ });
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
}
- function inferJsxTypeArguments(node, signature, excludeArgument, context) {
+ function inferJsxTypeArguments(node, signature, checkMode, context) {
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context);
+ var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
inferTypes(context.inferences, checkAttrType, paramType);
return getInferredTypes(context);
}
- function inferTypeArguments(node, signature, args, excludeArgument, context) {
- // Clear out all the inference results from the last time inferTypeArguments was called on this context
- for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) {
- var inference = _a[_i];
- // As an optimization, we don't have to clear (and later recompute) inferred types
- // for type parameters that have already been fixed on the previous call to inferTypeArguments.
- // It would be just as correct to reset all of them. But then we'd be repeating the same work
- // for the type parameters that were fixed, namely the work done by getInferredType.
- if (!inference.isFixed) {
- inference.inferredType = undefined;
- }
- }
+ function inferTypeArguments(node, signature, args, checkMode, context) {
if (ts.isJsxOpeningLikeElement(node)) {
- return inferJsxTypeArguments(node, signature, excludeArgument, context);
+ return inferJsxTypeArguments(node, signature, checkMode, context);
}
// If a contextual type is available, infer from that type to the return type of the call expression. For
// example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
@@ -49204,10 +49821,11 @@
if (node.kind !== 152 /* Decorator */) {
var contextualType = getContextualType(node);
if (contextualType) {
- // We clone the contextual mapper to avoid disturbing a resolution in progress for an
+ // We clone the inference context to avoid disturbing a resolution in progress for an
// outer call expression. Effectively we just want a snapshot of whatever has been
// inferred for any outer call expression so far.
- var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node)));
+ var outerMapper = getMapperFromContext(cloneInferenceContext(getInferenceContext(node), 1 /* NoDefault */));
+ var instantiatedType = instantiateType(contextualType, outerMapper);
// If the contextual type is a generic function type with a single call signature, we
// instantiate the type with its own type parameters and type arguments. This ensures that
// the type parameters are not erased to type any during type inference such that they can
@@ -49222,6 +49840,9 @@
var inferenceTargetType = getReturnTypeOfSignature(signature);
// Inferences made from return types have lower priority than all other inferences.
inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */);
+ // Create a type mapper for instantiating generic contextual types using the inferences made
+ // from the return type.
+ context.returnMapper = getMapperFromContext(cloneInferredPartOfContext(context));
}
}
var thisType = getThisTypeOfSignature(signature);
@@ -49236,10 +49857,7 @@
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- // For context sensitive arguments we pass the identityMapper, which is a signal to treat all
- // context sensitive function expressions as wildcards
- var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
- var argType = checkExpressionWithContextualType(arg, paramType, mapper);
+ var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
inferTypes(context.inferences, argType, paramType);
}
}
@@ -49263,7 +49881,7 @@
// and the argument are ...x forms.
return arg.kind === 215 /* SyntheticExpression */ ?
createArrayType(arg.type) :
- getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context));
+ getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
}
}
var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType;
@@ -49271,7 +49889,7 @@
var types = [];
var spreadIndex = -1;
for (var i = index; i < argCount; i++) {
- var argType = checkExpressionWithContextualType(args[i], contextualType, context);
+ var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
if (spreadIndex < 0 && isSpreadArgument(args[i])) {
spreadIndex = i - index;
}
@@ -49321,19 +49939,18 @@
* @param node a JSX opening-like element we are trying to figure its call signature
* @param signature a candidate signature we are trying whether it is a call signature
* @param relation a relationship to check parameter and argument type
- * @param excludeArgument
*/
- function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors) {
// Stateless function components can have maximum of three arguments: "props", "context", and "updater".
// However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
// can be specified by users through attributes property.
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined);
+ var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes);
}
- function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignature(node, args, signature, relation, checkMode, reportErrors) {
if (ts.isJsxOpeningLikeElement(node)) {
- return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors);
+ return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors);
}
var thisType = getThisTypeOfSignature(signature);
if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) {
@@ -49355,11 +49972,11 @@
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
- // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter),
+ var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
+ // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
// 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;
+ var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
return false;
}
@@ -49516,25 +50133,41 @@
if (argCount <= max && hasSpreadArgument) {
argCount--;
}
+ var spanArray;
var related;
+ var error = hasRestParameter || hasSpreadArgument ? 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 : ts.Diagnostics.Expected_0_arguments_but_got_1;
if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
if (paramDecl) {
related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined);
}
}
- 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;
- var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount);
- return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1;
- }
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);
}
- var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount);
- return related ? addRelatedInfo(diagnostic, related) : diagnostic;
+ if (!hasSpreadArgument && argCount < min) {
+ var diagnostic_1 = ts.createDiagnosticForNode(node, error, paramRange, argCount);
+ return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
+ }
+ if (hasRestParameter || hasSpreadArgument) {
+ spanArray = ts.createNodeArray(args);
+ if (hasSpreadArgument && argCount) {
+ var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
+ spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
+ }
+ }
+ else {
+ spanArray = ts.createNodeArray(args.slice(max));
+ }
+ spanArray.pos = ts.first(spanArray).pos;
+ spanArray.end = ts.last(spanArray).end;
+ if (spanArray.end === spanArray.pos) {
+ spanArray.end++;
+ }
+ var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
+ return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
}
function getTypeArgumentArityError(node, signatures, typeArguments) {
var argCount = typeArguments.length;
@@ -49564,7 +50197,7 @@
}
return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
}
- function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) {
+ function resolveCall(node, signatures, candidatesOutArray, checkMode, fallbackError) {
var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */;
var isDecorator = node.kind === 152 /* Decorator */;
var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
@@ -49600,7 +50233,7 @@
// For a decorator, no arguments are susceptible to contextual typing due to the fact
// decorators are applied to a declaration by the emitter, and not to an expression.
var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
- var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined;
+ var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
// The following variables are captured and modified by calls to chooseOverload.
// If overload resolution or type argument inference fails, we want to report the
// best error possible. The best error is one which says that an argument was not
@@ -49628,7 +50261,7 @@
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 = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
+ var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 191 /* 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
@@ -49654,12 +50287,7 @@
// skip the checkApplicableSignature check.
if (reportErrors) {
if (candidateForArgumentError) {
- // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...]
- // The importance of excludeArgument is to prevent us from typing function expression parameters
- // in arguments too early. If possible, we'd like to only type them once we know the correct
- // overload. However, this matters for the case where the call is correct. When the call is
- // 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);
+ checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, 0 /* Normal */, /*reportErrors*/ true);
}
else if (candidateForArgumentArityError) {
diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
@@ -49691,7 +50319,7 @@
if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
return undefined;
}
- if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false)) {
candidateForArgumentError = candidate;
return undefined;
}
@@ -49715,9 +50343,10 @@
}
else {
inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
+ typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
+ argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
}
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// 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 (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -49728,21 +50357,21 @@
else {
checkCandidate = candidate;
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
}
continue;
}
- if (excludeArgument) {
+ if (argCheckMode) {
// If one or more context sensitive arguments were excluded, we start including
// them now (and keeping do so for any subsequent candidates) and perform a second
// round of type inference and applicability checking for this particular candidate.
- excludeArgument = undefined;
+ argCheckMode = 0 /* Normal */;
if (inferenceContext) {
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// 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 (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -49750,7 +50379,7 @@
continue;
}
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
@@ -49764,20 +50393,6 @@
return undefined;
}
}
- function getExcludeArgument(args) {
- var excludeArgument;
- // We do not need to call `getEffectiveArgumentCount` here as it only
- // applies when calculating the number of arguments for a decorator.
- for (var i = 0; i < args.length; i++) {
- if (isContextSensitive(args[i])) {
- if (!excludeArgument) {
- excludeArgument = new Array(args.length);
- }
- excludeArgument[i] = true;
- }
- }
- return excludeArgument;
- }
// 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) {
@@ -49866,7 +50481,7 @@
}
function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext);
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
return createSignatureInstantiation(candidate, typeArgumentTypes);
}
function getLongestCandidateIndex(candidates, argsCount) {
@@ -49885,7 +50500,7 @@
}
return maxParamsIndex;
}
- function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveCallExpression(node, candidatesOutArray, checkMode) {
if (node.expression.kind === 98 /* SuperKeyword */) {
var superType = checkSuperExpression(node.expression);
if (isTypeAny(superType)) {
@@ -49901,7 +50516,7 @@
var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
if (baseTypeNode) {
var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
- return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, baseConstructors, candidatesOutArray, checkMode);
}
}
return resolveUntypedCall(node);
@@ -49951,12 +50566,31 @@
}
return resolveErrorCall(node);
}
+ // When a call to a generic function is an argument to an outer call to a generic function for which
+ // inference is in process, we have a choice to make. If the inner call relies on inferences made from
+ // its contextual type to its return type, deferring the inner call processing allows the best possible
+ // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
+ // the inner call, the inner call should be processed early. There's no sure way to know which choice is
+ // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
+ // If no type arguments are specified in the inner call and at least one call signature is generic and
+ // returns a function type, we choose to defer processing. This narrowly permits function composition
+ // operators to flow inferences through return types, but otherwise processes calls right away. We
+ // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
+ // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
+ // from which we never make inferences).
+ if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
+ skippedGenericFunction(node, checkMode);
+ return resolvingSignature;
+ }
// If the function is explicitly marked with `@class`, then it must be constructed.
if (callSignatures.some(function (sig) { return ts.isInJSFile(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);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
+ }
+ function isGenericFunctionReturningFunction(signature) {
+ return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
}
/**
* TS 1.0 spec: 4.12
@@ -49968,7 +50602,7 @@
return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
!numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
}
- function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveNewExpression(node, candidatesOutArray, checkMode) {
if (node.arguments && languageVersion < 1 /* ES5 */) {
var spreadIndex = getSpreadArgumentIndex(node.arguments);
if (spreadIndex >= 0) {
@@ -50016,7 +50650,7 @@
error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
return resolveErrorCall(node);
}
- return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, constructSignatures, candidatesOutArray, checkMode);
}
// 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
@@ -50024,7 +50658,7 @@
// 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, isForSignatureHelp);
+ var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode);
if (!noImplicitAny) {
if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
@@ -50046,13 +50680,12 @@
var firstBase = baseTypes[0];
if (firstBase.flags & 2097152 /* Intersection */) {
var types = firstBase.types;
- var mixinCount = ts.countWhere(types, isMixinConstructorType);
+ var mixinFlags = findMixins(types);
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 (!mixinFlags[i]) {
if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
if (intersectionMember.symbol === target) {
return true;
@@ -50062,6 +50695,7 @@
}
}
}
+ i++;
}
return false;
}
@@ -50105,7 +50739,7 @@
var diagnostic = 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, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
+ invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
}
function invocationErrorRecovery(apparentType, kind, diagnostic) {
if (!apparentType.symbol) {
@@ -50118,10 +50752,10 @@
var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
if (!sigs || !sigs.length)
return;
- 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));
+ 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, isForSignatureHelp) {
+ function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
var tagType = checkExpression(node.tag);
var apparentType = getApparentType(tagType);
if (apparentType === errorType) {
@@ -50137,7 +50771,7 @@
invocationError(node, apparentType, 0 /* Call */);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
}
/**
* Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
@@ -50162,7 +50796,7 @@
/**
* Resolves a decorator as if it were a call expression.
*/
- function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveDecorator(node, candidatesOutArray, checkMode) {
var funcType = checkExpression(node.expression);
var apparentType = getApparentType(funcType);
if (apparentType === errorType) {
@@ -50187,7 +50821,7 @@
invocationErrorRecovery(apparentType, 0 /* Call */, diag);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode, headMessage);
}
function createSignatureForJSXIntrinsic(node, result) {
var namespace = getJsxNamespaceAt(node);
@@ -50206,11 +50840,11 @@
/*hasRestparameter*/ false,
/*hasLiteralTypes*/ false);
}
- function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
var fakeSignature = createSignatureForJSXIntrinsic(node, result);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes);
+ checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
return fakeSignature;
}
var exprTypes = checkExpression(node.tagName);
@@ -50227,7 +50861,7 @@
error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
return resolveErrorCall(node);
}
- return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, signatures, candidatesOutArray, checkMode);
}
/**
* Sometimes, we have a decorator that could accept zero arguments,
@@ -50241,19 +50875,19 @@
signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
});
}
- function resolveSignature(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveSignature(node, candidatesOutArray, checkMode) {
switch (node.kind) {
case 191 /* CallExpression */:
- return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveCallExpression(node, candidatesOutArray, checkMode);
case 192 /* NewExpression */:
- return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveNewExpression(node, candidatesOutArray, checkMode);
case 193 /* TaggedTemplateExpression */:
- return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
case 152 /* Decorator */:
- return resolveDecorator(node, candidatesOutArray, isForSignatureHelp);
+ return resolveDecorator(node, candidatesOutArray, checkMode);
case 262 /* JsxOpeningElement */:
case 261 /* JsxSelfClosingElement */:
- return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp);
+ return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
}
throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
}
@@ -50264,8 +50898,7 @@
* 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, isForSignatureHelp) {
- if (isForSignatureHelp === void 0) { isForSignatureHelp = false; }
+ function getResolvedSignature(node, candidatesOutArray, checkMode) {
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,
@@ -50276,11 +50909,15 @@
return cached;
}
links.resolvedSignature = resolvingSignature;
- var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp);
+ var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
+ // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
+ // resolution should be deferred.
+ if (result !== resolvingSignature) {
// 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.
links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ }
return result;
}
/**
@@ -50356,10 +50993,15 @@
* @param node The call/new expression to be checked.
* @returns On success, the expression's signature's return type. On failure, anyType.
*/
- function checkCallExpression(node) {
+ function checkCallExpression(node, checkMode) {
if (!checkGrammarTypeArguments(node, node.typeArguments))
checkGrammarArguments(node.arguments);
- var signature = getResolvedSignature(node);
+ var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
+ if (signature === resolvingSignature) {
+ // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
+ // returns a function type. We defer checking and return nonInferrableType.
+ return nonInferrableType;
+ }
if (node.expression.kind === 98 /* SuperKeyword */) {
return voidType;
}
@@ -50459,7 +51101,7 @@
var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
anonymousSymbol.type = defaultContainingObject;
- synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0) : defaultContainingObject;
+ synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
}
else {
synthType.syntheticType = type;
@@ -50506,9 +51148,37 @@
function checkAssertion(node) {
return checkAssertionWorker(node, node.type, node.expression);
}
+ function isValidConstAssertionArgument(node) {
+ switch (node.kind) {
+ case 10 /* StringLiteral */:
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 8 /* NumericLiteral */:
+ case 9 /* BigIntLiteral */:
+ case 102 /* TrueKeyword */:
+ case 87 /* FalseKeyword */:
+ case 187 /* ArrayLiteralExpression */:
+ case 188 /* ObjectLiteralExpression */:
+ return true;
+ case 195 /* ParenthesizedExpression */:
+ return isValidConstAssertionArgument(node.expression);
+ case 202 /* PrefixUnaryExpression */:
+ var op = node.operator;
+ var arg = node.operand;
+ return op === 39 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
+ op === 38 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
+ }
+ return false;
+ }
function checkAssertionWorker(errNode, type, expression, checkMode) {
- var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode)));
+ var exprType = checkExpression(expression, checkMode);
+ if (ts.isConstTypeReference(type)) {
+ if (!isValidConstAssertionArgument(expression)) {
+ error(expression, ts.Diagnostics.A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal);
+ }
+ return getRegularTypeOfLiteralType(exprType);
+ }
checkSourceElement(type);
+ exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
var targetType = getTypeFromTypeNode(type);
if (produceDiagnostics && targetType !== errorType) {
var widenedType = getWidenedType(exprType);
@@ -50547,7 +51217,7 @@
}
}
function checkImportMetaProperty(node) {
- if (languageVersion < 6 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) {
+ if (languageVersion < 7 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) {
error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options);
}
var file = ts.getSourceFileOfNode(node);
@@ -50575,7 +51245,7 @@
if (isTupleType(restType)) {
var associatedNames = restType.target.associatedNames;
var index = pos - paramCount;
- return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index;
+ return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
}
return restParameter.escapedName;
}
@@ -50588,33 +51258,37 @@
return getTypeOfParameter(signature.parameters[pos]);
}
if (signature.hasRestParameter) {
+ // We want to return the value undefined for an out of bounds parameter position,
+ // so we need to check bounds here before calling getIndexedAccessType (which
+ // otherwise would return the type 'undefined').
var restType = getTypeOfSymbol(signature.parameters[paramCount]);
- if (isTupleType(restType)) {
- if (pos - paramCount < getLengthOfTupleType(restType)) {
- return restType.typeArguments[pos - paramCount];
- }
- return getRestTypeOfTupleType(restType);
+ var index = pos - paramCount;
+ if (!isTupleType(restType) || restType.target.hasRestElement || index < (restType.typeArguments || ts.emptyArray).length) {
+ return getIndexedAccessType(restType, getLiteralType(index));
}
- return getIndexTypeOfType(restType, 1 /* Number */);
}
return undefined;
}
function getRestTypeAtPosition(source, pos) {
var paramCount = getParameterCount(source);
var restType = getEffectiveRestType(source);
- if (restType && pos === paramCount - 1) {
+ var nonRestCount = paramCount - (restType ? 1 : 0);
+ if (restType && pos === nonRestCount) {
return restType;
}
- var start = restType ? Math.min(pos, paramCount - 1) : pos;
var types = [];
var names = [];
- for (var i = start; i < paramCount; i++) {
+ for (var i = pos; i < nonRestCount; i++) {
types.push(getTypeAtPosition(source, i));
names.push(getParameterNameAtPosition(source, i));
}
+ if (restType) {
+ types.push(getIndexedAccessType(restType, numberType));
+ names.push(getParameterNameAtPosition(source, nonRestCount));
+ }
var minArgumentCount = getMinArgumentCount(source);
- var minLength = minArgumentCount < start ? 0 : minArgumentCount - start;
- return createTupleType(types, minLength, !!restType, names);
+ var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos;
+ return createTupleType(types, minLength, !!restType, /*readonly*/ false, names);
}
function getParameterCount(signature) {
var length = signature.parameters.length;
@@ -50662,16 +51336,27 @@
function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
}
- function inferFromAnnotatedParameters(signature, context, mapper) {
+ function inferFromAnnotatedParameters(signature, context, inferenceContext) {
var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
for (var i = 0; i < len; i++) {
var declaration = signature.parameters[i].valueDeclaration;
if (declaration.type) {
var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
if (typeNode) {
- inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
+ inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
+ }
}
}
+ var restType = getEffectiveRestType(context);
+ if (restType && restType.flags & 262144 /* TypeParameter */) {
+ // The contextual signature has a generic rest parameter. We first instantiate the contextual
+ // signature (without fixing type parameters) and assign types to contextually typed parameters.
+ var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
+ assignContextualParameterTypes(signature, instantiatedContext);
+ // We then infer from a tuple type representing the parameters that correspond to the contextual
+ // rest parameter.
+ var restPos = getParameterCount(context) - 1;
+ inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
}
}
function assignContextualParameterTypes(signature, context) {
@@ -50773,7 +51458,7 @@
var functionFlags = ts.getFunctionFlags(func);
var type;
if (func.body.kind !== 218 /* Block */) {
- type = checkExpressionCached(func.body, checkMode);
+ type = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -50951,7 +51636,7 @@
ts.forEachReturnStatement(func.body, function (returnStatement) {
var expr = returnStatement.expression;
if (expr) {
- var type = checkExpressionCached(expr, checkMode);
+ var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51044,7 +51729,7 @@
ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
checkNodeDeferred(node);
// The identityMapper object is used to indicate that function expressions are wildcards
- if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) {
+ if (checkMode && checkMode & 4 /* 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);
@@ -51054,7 +51739,7 @@
var returnType = getReturnTypeFromBody(node, checkMode);
var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
- returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */;
+ returnOnlyType.objectFlags |= 524288 /* NonInferrableType */;
return links_1.contextFreeType = returnOnlyType;
}
return anyFunctionType;
@@ -51080,12 +51765,12 @@
if (contextualSignature) {
var signature = getSignaturesOfType(type, 0 /* Call */)[0];
if (isContextSensitive(node)) {
- var contextualMapper = getContextualMapper(node);
- if (checkMode === 2 /* Inferential */) {
- inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper);
+ var inferenceContext = getInferenceContext(node);
+ if (checkMode && checkMode & 2 /* Inferential */) {
+ inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
}
- var instantiatedContextualSignature = contextualMapper === identityMapper ?
- contextualSignature : instantiateSignature(contextualSignature, contextualMapper);
+ var instantiatedContextualSignature = inferenceContext ?
+ instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
assignContextualParameterTypes(signature, instantiatedContextualSignature);
}
if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
@@ -51351,13 +52036,13 @@
// Return true if type might be of the given kind. A union or intersection type might be of a given
// kind if at least one constituent type is of the given kind.
function maybeTypeOfKind(type, kind) {
- if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) {
+ if (type.flags & kind & ~131072 /* GenericMappedType */ || kind & 131072 /* GenericMappedType */ && isGenericMappedType(type)) {
return true;
}
if (type.flags & 3145728 /* UnionOrIntersection */) {
var types = type.types;
- for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
- var t = types_15[_i];
+ for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
+ var t = types_16[_i];
if (maybeTypeOfKind(t, kind)) {
return true;
}
@@ -51436,8 +52121,8 @@
if (strictNullChecks && properties.length === 0) {
return checkNonNullType(sourceType, node);
}
- for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) {
- var p = properties_6[_i];
+ for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
+ var p = properties_5[_i];
checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis);
}
return sourceType;
@@ -51461,7 +52146,7 @@
return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
}
else if (property.kind === 277 /* SpreadAssignment */) {
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(property, 4 /* Rest */);
}
var nonRestNames = [];
@@ -51956,7 +52641,7 @@
// Async generator functions prior to ESNext require the __await, __asyncDelegator,
// and __asyncValues helpers
if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ &&
- languageVersion < 6 /* ESNext */) {
+ languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */);
}
// Generator functions prior to ES2015 require the __values helper
@@ -52003,23 +52688,26 @@
}
return node;
}
- function checkExpressionWithContextualType(node, contextualType, contextualMapper) {
+ function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
var context = getContextNode(node);
var saveContextualType = context.contextualType;
- var saveContextualMapper = context.contextualMapper;
+ var saveInferenceContext = context.inferenceContext;
context.contextualType = contextualType;
- context.contextualMapper = contextualMapper;
- var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ :
- contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */;
- var result = checkExpression(node, checkMode);
+ context.inferenceContext = inferenceContext;
+ var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
+ // We strip literal freshness when an appropriate contextual type is present such that contextually typed
+ // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
+ // here would be to not mark contextually typed literals as fresh in the first place.
+ var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
+ getRegularTypeOfLiteralType(type) : type;
context.contextualType = saveContextualType;
- context.contextualMapper = saveContextualMapper;
+ context.inferenceContext = saveInferenceContext;
return result;
}
function checkExpressionCached(node, checkMode) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- if (checkMode) {
+ if (checkMode && checkMode !== 0 /* Normal */) {
return checkExpression(node, checkMode);
}
// When computing a type that we're going to cache, we need to ignore any ongoing control flow
@@ -52082,13 +52770,17 @@
}
return false;
}
- function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
- if (arguments.length === 2) {
- contextualType = getContextualType(node);
+ function isConstContext(node) {
+ var parent = node.parent;
+ return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
+ (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
+ (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
}
+ function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
var type = checkExpression(node, checkMode, forceTuple);
- return isTypeAssertion(node) ? type :
- getWidenedLiteralLikeTypeForContextualType(type, contextualType);
+ return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
+ isTypeAssertion(node) ? type :
+ getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
}
function checkPropertyAssignment(node, checkMode) {
// Do not use hasDynamicName here, because that returns false for well known symbols.
@@ -52112,20 +52804,129 @@
return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
}
function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
+ if (checkMode & 8 /* SkipGenericFunctions */) {
+ skippedGenericFunction(node, checkMode);
+ return anyFunctionType;
+ }
var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType));
if (contextualSignature && !contextualSignature.typeParameters) {
- return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node)));
+ var context = getInferenceContext(node);
+ // We have an expression that is an argument of a generic function for which we are performing
+ // type argument inference. The expression is of a function type with a single generic call
+ // signature and a contextual function type with a single non-generic call signature. Now check
+ // if the outer function returns a function type with a single non-generic call signature and
+ // if some of the outer function type parameters have no inferences so far. If so, we can
+ // potentially add inferred type parameters to the outer function return type.
+ var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature));
+ if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
+ // Instantiate the signature with its own type parameters as type arguments, possibly
+ // renaming the type parameters to ensure they have unique names.
+ var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
+ // Infer from the parameters of the instantiated signature to the parameters of the
+ // contextual signature starting with an empty set of inference candidates.
+ var inferences_2 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
+ applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
+ inferTypes(inferences_2, source, target, /*priority*/ 0, /*contravariant*/ true);
+ });
+ if (ts.some(inferences_2, hasInferenceCandidates)) {
+ // We have inference candidates, indicating that one or more type parameters are referenced
+ // in the parameter types of the contextual signature. Now also infer from the return type.
+ applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
+ inferTypes(inferences_2, source, target);
+ });
+ // If the type parameters for which we produced candidates do not have any inferences yet,
+ // we adopt the new inference candidates and add the type parameters of the expression type
+ // to the set of inferred type parameters for the outer function return type.
+ if (!hasOverlappingInferences(context.inferences, inferences_2)) {
+ mergeInferences(context.inferences, inferences_2);
+ context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
+ return getOrCreateTypeFromSignature(instantiatedSignature);
+ }
+ }
+ }
+ return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
}
}
}
}
return type;
}
+ function skippedGenericFunction(node, checkMode) {
+ if (checkMode & 2 /* Inferential */) {
+ // We have skipped a generic function during inferential typing. Obtain the inference context and
+ // indicate this has occurred such that we know a second pass of inference is be needed.
+ var context = getInferenceContext(node);
+ context.flags |= 4 /* SkippedGenericFunction */;
+ }
+ }
+ function hasInferenceCandidates(info) {
+ return !!(info.candidates || info.contraCandidates);
+ }
+ function hasOverlappingInferences(a, b) {
+ for (var i = 0; i < a.length; i++) {
+ if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ function mergeInferences(target, source) {
+ for (var i = 0; i < target.length; i++) {
+ if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
+ target[i] = source[i];
+ }
+ }
+ }
+ function getUniqueTypeParameters(context, typeParameters) {
+ var result = [];
+ var oldTypeParameters;
+ var newTypeParameters;
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var tp = typeParameters_2[_i];
+ var name = tp.symbol.escapedName;
+ if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
+ var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
+ var symbol = createSymbol(262144 /* TypeParameter */, newName);
+ var newTypeParameter = createTypeParameter(symbol);
+ newTypeParameter.target = tp;
+ oldTypeParameters = ts.append(oldTypeParameters, tp);
+ newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
+ result.push(newTypeParameter);
+ }
+ else {
+ result.push(tp);
+ }
+ }
+ if (newTypeParameters) {
+ var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
+ for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
+ var tp = newTypeParameters_1[_a];
+ tp.mapper = mapper;
+ }
+ }
+ return result;
+ }
+ function hasTypeParameterByName(typeParameters, name) {
+ return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
+ }
+ function getUniqueTypeParameterName(typeParameters, baseName) {
+ var len = baseName.length;
+ while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
+ len--;
+ var s = baseName.slice(0, len);
+ for (var index = 1; true; index++) {
+ var augmentedName = (s + index);
+ if (!hasTypeParameterByName(typeParameters, augmentedName)) {
+ return augmentedName;
+ }
+ }
+ }
/**
* Returns the type of an expression. Unlike checkExpression, this function is simply concerned
* with computing the type and may not fully check all contained sub-expressions for errors.
@@ -52143,7 +52944,7 @@
return getReturnTypeOfSignature(signature);
}
}
- else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) {
+ else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
return getTypeFromTypeNode(expr.type);
}
// Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions
@@ -52165,27 +52966,22 @@
}
var saveContextualType = node.contextualType;
node.contextualType = anyType;
- var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */);
+ var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
node.contextualType = saveContextualType;
return type;
}
- // 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
- // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function
- // object, it serves as an indicator that all contained function and arrow expressions should be considered to
- // have the wildcard function type; this form of type check is used during overload resolution to exclude
- // contextually typed function and arrow expressions in the initial phase.
function checkExpression(node, checkMode, forceTuple) {
- var type;
- if (node.kind === 148 /* QualifiedName */) {
- type = checkQualifiedName(node);
- }
- else {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
- type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
- }
+ var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
if (isConstEnumObjectType(type)) {
+ checkConstEnumAccess(node, type);
+ }
+ currentNode = saveCurrentNode;
+ return type;
+ }
+ function checkConstEnumAccess(node, type) {
// enum object type for const enums are only permitted in:
// - 'left' in property access
// - 'object' in indexed access
@@ -52197,8 +52993,13 @@
if (!ok) {
error(node, ts.Diagnostics.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);
}
+ if (compilerOptions.isolatedModules) {
+ ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
+ var constEnumDeclaration = type.symbol.valueDeclaration;
+ if (constEnumDeclaration.flags & 4194304 /* Ambient */) {
+ error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
+ }
}
- return type;
}
function checkParenthesizedExpression(node, checkMode) {
var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
@@ -52240,6 +53041,8 @@
return checkObjectLiteral(node, checkMode);
case 189 /* PropertyAccessExpression */:
return checkPropertyAccessExpression(node);
+ case 148 /* QualifiedName */:
+ return checkQualifiedName(node);
case 190 /* ElementAccessExpression */:
return checkIndexedAccess(node);
case 191 /* CallExpression */:
@@ -52248,7 +53051,7 @@
}
/* falls through */
case 192 /* NewExpression */:
- return checkCallExpression(node);
+ return checkCallExpression(node, checkMode);
case 193 /* TaggedTemplateExpression */:
return checkTaggedTemplateExpression(node);
case 195 /* ParenthesizedExpression */:
@@ -52313,9 +53116,8 @@
checkSourceElement(node.constraint);
checkSourceElement(node.default);
var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
- if (!hasNonCircularBaseConstraint(typeParameter)) {
- error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter));
- }
+ // Resolve base constraint to reveal circularity errors
+ getBaseConstraintOfType(typeParameter);
if (!hasNonCircularTypeParameterDefault(typeParameter)) {
error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
}
@@ -52357,7 +53159,7 @@
}
// 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) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) {
+ if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) {
error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
}
}
@@ -52368,7 +53170,8 @@
error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
return;
}
- var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent));
+ var signature = getSignatureFromDeclaration(parent);
+ var typePredicate = getTypePredicateOfSignature(signature);
if (!typePredicate) {
return;
}
@@ -52379,12 +53182,12 @@
}
else {
if (typePredicate.parameterIndex >= 0) {
- if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) {
+ if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) {
error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
}
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]), node.type,
+ checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type,
/*headMessage*/ undefined, leadingError);
}
}
@@ -52451,7 +53254,7 @@
var functionFlags = ts.getFunctionFlags(node);
if (!(functionFlags & 4 /* Invalid */)) {
// Async generators prior to ESNext require the __await and __asyncGenerator helpers
- if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) {
+ if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */);
}
// Async functions prior to ES2017 require the __awaiter helper
@@ -52508,7 +53311,7 @@
checkAsyncFunctionReturnType(node, returnTypeNode);
}
}
- if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) {
+ if (node.kind !== 162 /* IndexSignature */ && node.kind !== 294 /* JSDocFunctionType */) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -53187,7 +53990,7 @@
for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) {
var signature = signatures_6[_a];
if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
- error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation);
+ ts.addRelatedInfo(error(signature.declaration, ts.Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), ts.createDiagnosticForNode(bodyDeclaration, ts.Diagnostics.The_implementation_signature_is_declared_here));
break;
}
}
@@ -53264,8 +54067,8 @@
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
// A jsdoc typedef and callback are, by definition, type aliases
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return 2 /* ExportType */;
case 244 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
@@ -53274,7 +54077,7 @@
case 240 /* ClassDeclaration */:
case 243 /* EnumDeclaration */:
return 2 /* ExportType */ | 1 /* ExportValue */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
case 254 /* ExportAssignment */:
// Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
@@ -53639,8 +54442,8 @@
}
function getEntityNameForDecoratorMetadataFromTypeList(types) {
var commonEntityName;
- for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
- var typeNode = types_16[_i];
+ for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
+ var typeNode = types_17[_i];
while (typeNode.kind === 177 /* ParenthesizedType */) {
typeNode = typeNode.type; // Skip parens if need be
}
@@ -53915,7 +54718,7 @@
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
case 246 /* CaseBlock */:
@@ -54008,8 +54811,8 @@
return;
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];
+ for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
+ var typeParameter = typeParameters_3[_i];
if (!isTypeParameterUnused(typeParameter))
continue;
var name = ts.idText(typeParameter.name);
@@ -54262,7 +55065,7 @@
}
// 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 === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
+ if (parent.kind === 284 /* 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));
}
@@ -54277,7 +55080,7 @@
}
// 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 === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
+ if (parent.kind === 284 /* 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));
}
@@ -54334,7 +55137,7 @@
(container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) ||
container.kind === 245 /* ModuleBlock */ ||
container.kind === 244 /* ModuleDeclaration */ ||
- container.kind === 279 /* SourceFile */);
+ container.kind === 284 /* 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
@@ -54434,7 +55237,7 @@
}
}
if (node.kind === 186 /* BindingElement */) {
- if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) {
+ if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 4 /* Rest */);
}
// check computed properties inside property names of binding elements
@@ -54445,7 +55248,7 @@
var parent = node.parent.parent;
var parentType = getTypeForBindingElementParent(parent);
var name = node.propertyName || node.name;
- if (!ts.isBindingPattern(name) && parentType) {
+ if (parentType && !ts.isBindingPattern(name)) {
var exprType = getLiteralTypeFromPropertyName(name);
if (isTypeUsableAsPropertyName(exprType)) {
var nameText = getPropertyNameFromType(exprType);
@@ -54632,7 +55435,7 @@
checkGrammarForInOrForOfStatement(node);
if (node.awaitModifier) {
var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
- if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) {
+ if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 7 /* ESNext */) {
// for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */);
}
@@ -55077,7 +55880,7 @@
// If the function has a return type, but promisedType is
// undefined, an error will be reported in checkAsyncFunctionReturnType
// so we don't need to report one here.
- checkTypeAssignableTo(awaitedType, promisedType, node);
+ checkTypeAssignableToAndOptionallyElaborate(awaitedType, promisedType, node, node.expression);
}
}
else {
@@ -55677,8 +56480,8 @@
for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
var base = baseTypes_2[_i];
var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
- for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) {
- var prop = properties_7[_a];
+ for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
+ var prop = properties_6[_a];
var existing = seen.get(prop.escapedName);
if (!existing) {
seen.set(prop.escapedName, { prop: prop, containingType: base });
@@ -55948,10 +56751,6 @@
checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
checkExportsOnMergedDeclarations(node);
computeEnumMemberValues(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);
- }
// Spec 2014 - Section 9.3:
// It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
// and when an enum type has multiple declarations, only one declaration is permitted to omit a value
@@ -55962,9 +56761,10 @@
var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
if (node === firstDeclaration) {
if (enumSymbol.declarations.length > 1) {
+ var enumIsConst_1 = ts.isEnumConst(node);
// check that const is placed\omitted on all enum declarations
ts.forEach(enumSymbol.declarations, function (decl) {
- if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) {
+ if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
}
});
@@ -56045,8 +56845,8 @@
var symbol = getSymbolOfNode(node);
// The following checks only apply on a non-ambient instantiated module declaration.
if (symbol.flags & 512 /* ValueModule */
- && symbol.declarations.length > 1
&& !inAmbientContext
+ && symbol.declarations.length > 1
&& isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
if (firstNonAmbientClassOrFunc) {
@@ -56187,7 +56987,7 @@
return false;
}
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule) {
error(moduleName, node.kind === 255 /* ExportDeclaration */ ?
ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
@@ -56318,7 +57118,7 @@
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ &&
!node.moduleSpecifier && node.flags & 4194304 /* Ambient */;
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
}
}
@@ -56335,7 +57135,7 @@
}
}
function checkGrammarModuleElementContext(node, errorMessage) {
- var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
+ var isInAppropriateContext = node.parent.kind === 284 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
if (!isInAppropriateContext) {
grammarErrorOnFirstToken(node, errorMessage);
}
@@ -56364,7 +57164,7 @@
// If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
return;
}
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
if (node.isExportEquals) {
error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
@@ -56457,9 +57257,14 @@
!!declaration.body;
}
function checkSourceElement(node) {
- if (!node) {
- return;
+ if (node) {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
+ checkSourceElementWorker(node);
+ currentNode = saveCurrentNode;
+ }
}
+ function checkSourceElementWorker(node) {
if (ts.isInJSFile(node)) {
ts.forEach(node.jsDoc, function (_a) {
var tags = _a.tags;
@@ -56529,32 +57334,32 @@
return checkInferType(node);
case 183 /* ImportType */:
return checkImportType(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return checkJSDocAugmentsTag(node);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return checkJSDocTypeAliasTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return checkJSDocTemplateTag(node);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return checkJSDocTypeTag(node);
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
return checkJSDocParameterTag(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
checkJSDocFunctionType(node);
// falls through
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
- case 292 /* JSDocTypeLiteral */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
+ case 297 /* JSDocTypeLiteral */:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
checkJSDocVariadicType(node);
return;
- case 283 /* JSDocTypeExpression */:
+ case 288 /* JSDocTypeExpression */:
return checkSourceElement(node.type);
case 180 /* IndexedAccessType */:
return checkIndexedAccessType(node);
@@ -56708,10 +57513,13 @@
}
function checkDeferredNodes(context) {
var links = getNodeLinks(context);
- if (!links.deferredNodes) {
- return;
+ if (links.deferredNodes) {
+ links.deferredNodes.forEach(checkDeferredNode);
}
- links.deferredNodes.forEach(function (node) {
+ }
+ function checkDeferredNode(node) {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
switch (node.kind) {
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
@@ -56733,7 +57541,7 @@
checkJsxElementDeferred(node);
break;
}
- });
+ currentNode = saveCurrentNode;
}
function checkSourceFile(node) {
ts.performance.mark("beforeCheck");
@@ -56808,7 +57616,7 @@
throwIfNonDiagnosticsProducing();
if (sourceFile) {
// Some global diagnostics are deferred until they are needed and
- // may not be reported in the firt call to getGlobalDiagnostics.
+ // may not be reported in the first call to getGlobalDiagnostics.
// We should catch these changes and report them.
var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
@@ -56859,7 +57667,7 @@
copySymbols(location.locals, meaning);
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
// falls through
@@ -57078,10 +57886,10 @@
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 299 /* JSDocParameterTag */) {
+ if (entityName.parent.kind === 304 /* JSDocParameterTag */) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) {
+ if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 308 /* JSDocTemplateTag */) {
ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true.
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -57123,7 +57931,7 @@
return undefined;
}
function getSymbolAtLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
}
var parent = node.parent;
@@ -57465,7 +58273,7 @@
}
var parentSymbol_1 = getParentOfSymbol(symbol);
if (parentSymbol_1) {
- if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) {
+ if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 284 /* 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.
@@ -57492,7 +58300,7 @@
return undefined;
}
function isSymbolOfDeclarationWithCollidingName(symbol) {
- if (symbol.flags & 418 /* BlockScoped */) {
+ if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
var links = getSymbolLinks(symbol);
if (links.isDeclarationWithCollidingName === undefined) {
var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
@@ -57580,7 +58388,7 @@
}
function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
- if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
+ if (node === undefined || node.parent.kind !== 284 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
// parent is not source file or it is not reference to internal module
return false;
}
@@ -58009,7 +58817,7 @@
break;
}
}
- if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
+ if (current.valueDeclaration && current.valueDeclaration.kind === 284 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
return false;
}
// check that at least one declaration of top level symbol originates from type declaration file
@@ -58042,7 +58850,7 @@
if (!moduleSymbol) {
return undefined;
}
- return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */);
+ return ts.getDeclarationOfKind(moduleSymbol, 284 /* SourceFile */);
}
function initializeTypeChecker() {
// Bind all source files and propagate errors
@@ -58120,7 +58928,7 @@
// autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
}
- globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1);
+ globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
if (augmentations) {
@@ -58156,8 +58964,8 @@
else {
// Otherwise issue top-level error since the files appear very identical in terms of what they contain
var list = ts.arrayFrom(conflictingSymbols.keys()).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)));
+ diagnostics.add(ts.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(ts.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;
@@ -58274,7 +59082,7 @@
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
}
else if (flags & 128 /* Abstract */) {
@@ -58297,7 +59105,7 @@
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
}
else if (node.kind === 151 /* Parameter */) {
@@ -58342,7 +59150,7 @@
flags |= 1 /* Export */;
break;
case 80 /* DefaultKeyword */:
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
}
@@ -58465,7 +59273,7 @@
case 151 /* Parameter */:
return false;
default:
- if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return false;
}
switch (node.kind) {
@@ -58553,10 +59361,10 @@
var nonSimpleParameters = getNonSimpleParameters(node.parameters);
if (ts.length(nonSimpleParameters)) {
ts.forEach(nonSimpleParameters, function (parameter) {
- addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
+ ts.addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
});
var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); });
- addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
+ ts.addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
return true;
}
}
@@ -58993,6 +59801,11 @@
return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
}
}
+ else if (node.operator === 133 /* ReadonlyKeyword */) {
+ if (node.type.kind !== 169 /* ArrayType */ && node.type.kind !== 170 /* TupleType */) {
+ return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(139 /* SymbolKeyword */));
+ }
+ }
}
function checkGrammarForInvalidDynamicName(node, message) {
if (isNonBindableDynamicName(node)) {
@@ -59383,7 +60196,7 @@
// 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 === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
var links_2 = getNodeLinks(node.parent);
// Check if the containing block ever report this error
if (!links_2.hasReportedStatementInAmbientContext) {
@@ -59423,7 +60236,7 @@
var literalType = ts.isLiteralTypeNode(node.parent) ||
ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
if (!literalType) {
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) {
return true;
}
@@ -59588,10 +60401,11 @@
return createLiteralFromNode(value);
}
ts.createLiteral = createLiteral;
- function createNumericLiteral(value) {
+ function createNumericLiteral(value, numericLiteralFlags) {
+ if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
var node = createSynthesizedNode(8 /* NumericLiteral */);
node.text = value;
- node.numericLiteralFlags = 0;
+ node.numericLiteralFlags = numericLiteralFlags;
return node;
}
ts.createNumericLiteral = createNumericLiteral;
@@ -61436,14 +62250,14 @@
// JSDoc
/* @internal */
function createJSDocTypeExpression(type) {
- var node = createSynthesizedNode(283 /* JSDocTypeExpression */);
+ var node = createSynthesizedNode(288 /* JSDocTypeExpression */);
node.type = type;
return node;
}
ts.createJSDocTypeExpression = createJSDocTypeExpression;
/* @internal */
function createJSDocTypeTag(typeExpression, comment) {
- var tag = createJSDocTag(302 /* JSDocTypeTag */, "type");
+ var tag = createJSDocTag(307 /* JSDocTypeTag */, "type");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61451,7 +62265,7 @@
ts.createJSDocTypeTag = createJSDocTypeTag;
/* @internal */
function createJSDocReturnTag(typeExpression, comment) {
- var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns");
+ var tag = createJSDocTag(305 /* JSDocReturnTag */, "returns");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61459,7 +62273,7 @@
ts.createJSDocReturnTag = createJSDocReturnTag;
/* @internal */
function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
- var tag = createJSDocTag(299 /* JSDocParameterTag */, "param");
+ var tag = createJSDocTag(304 /* JSDocParameterTag */, "param");
tag.typeExpression = typeExpression;
tag.name = name;
tag.isBracketed = isBracketed;
@@ -61469,7 +62283,7 @@
ts.createJSDocParamTag = createJSDocParamTag;
/* @internal */
function createJSDocComment(comment, tags) {
- var node = createSynthesizedNode(291 /* JSDocComment */);
+ var node = createSynthesizedNode(296 /* JSDocComment */);
node.comment = comment;
node.tags = tags;
return node;
@@ -61550,6 +62364,28 @@
return node;
}
ts.createJsxFragment = createJsxFragment;
+ function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
+ var node = createSynthesizedNode(11 /* JsxText */);
+ node.text = text;
+ node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
+ return node;
+ }
+ ts.createJsxText = createJsxText;
+ function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
+ return node.text !== text
+ || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
+ ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
+ : node;
+ }
+ ts.updateJsxText = updateJsxText;
+ function createJsxOpeningFragment() {
+ return createSynthesizedNode(265 /* JsxOpeningFragment */);
+ }
+ ts.createJsxOpeningFragment = createJsxOpeningFragment;
+ function createJsxJsxClosingFragment() {
+ return createSynthesizedNode(266 /* JsxClosingFragment */);
+ }
+ ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment;
function updateJsxFragment(node, openingFragment, children, closingFragment) {
return node.openingFragment !== openingFragment
|| node.children !== children
@@ -61728,7 +62564,7 @@
(typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
(libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
(hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
- var updated = createSynthesizedNode(279 /* SourceFile */);
+ var updated = createSynthesizedNode(284 /* SourceFile */);
updated.flags |= node.flags;
updated.statements = createNodeArray(statements);
updated.endOfFileToken = node.endOfFileToken;
@@ -61812,7 +62648,7 @@
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(307 /* NotEmittedStatement */);
+ var node = createSynthesizedNode(312 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
@@ -61824,7 +62660,7 @@
*/
/* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(316 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -61836,7 +62672,7 @@
*/
/* @internal */
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(310 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(315 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -61851,7 +62687,7 @@
* @param location The location for the expression. Defaults to the positions from "original" if provided.
*/
function createPartiallyEmittedExpression(expression, original) {
- var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */);
+ var node = createSynthesizedNode(313 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -61867,7 +62703,7 @@
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
function flattenCommaElements(node) {
if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
- if (node.kind === 309 /* CommaListExpression */) {
+ if (node.kind === 314 /* CommaListExpression */) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
@@ -61877,7 +62713,7 @@
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(309 /* CommaListExpression */);
+ var node = createSynthesizedNode(314 /* CommaListExpression */);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -61890,33 +62726,197 @@
ts.updateCommaList = updateCommaList;
function createBundle(sourceFiles, prepends) {
if (prepends === void 0) { prepends = ts.emptyArray; }
- var node = ts.createNode(280 /* Bundle */);
+ var node = ts.createNode(285 /* Bundle */);
node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, map) {
- var node = ts.createNode(281 /* UnparsedSource */);
+ var allUnscopedEmitHelpers;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
+ ts.valuesHelper,
+ ts.readHelper,
+ ts.spreadHelper,
+ ts.restHelper,
+ ts.decorateHelper,
+ ts.metadataHelper,
+ ts.paramHelper,
+ ts.awaiterHelper,
+ ts.assignHelper,
+ ts.awaitHelper,
+ ts.asyncGeneratorHelper,
+ ts.asyncDelegator,
+ ts.asyncValues,
+ ts.extendsHelper,
+ ts.templateObjectHelper,
+ ts.generatorHelper,
+ ts.importStarHelper,
+ ts.importDefaultHelper
+ ], function (helper) { return helper.name; }));
+ }
+ function createUnparsedSource() {
+ var node = ts.createNode(286 /* UnparsedSource */);
+ node.prologues = ts.emptyArray;
+ node.referencedFiles = ts.emptyArray;
+ node.libReferenceDirectives = ts.emptyArray;
+ node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
+ return node;
+ }
+ function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
+ var node = createUnparsedSource();
+ var stripInternal;
+ var bundleFileInfo;
if (!ts.isString(textOrInputFiles)) {
ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
- node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath;
+ node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
Object.defineProperties(node, {
text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
});
+ if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
+ node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
+ ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
+ stripInternal = mapTextOrStripInternal;
+ bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
+ if (node.oldFileOfCurrentEmit) {
+ parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo));
+ return node;
+ }
+ }
}
else {
+ node.fileName = "";
node.text = textOrInputFiles;
node.sourceMapPath = mapPathOrType;
- node.sourceMapText = map;
+ node.sourceMapText = mapTextOrStripInternal;
}
+ ts.Debug.assert(!node.oldFileOfCurrentEmit);
+ parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
return node;
}
ts.createUnparsedSourceFile = createUnparsedSourceFile;
- function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapText) {
- var node = ts.createNode(282 /* InputFiles */);
+ function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
+ var prologues;
+ var helpers;
+ var referencedFiles;
+ var typeReferenceDirectives;
+ var libReferenceDirectives;
+ var texts;
+ for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "prologue" /* Prologue */:
+ (prologues || (prologues = [])).push(createUnparsedNode(section, node));
+ break;
+ case "emitHelpers" /* EmitHelpers */:
+ (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ node.hasNoDefaultLib = true;
+ break;
+ case "reference" /* Reference */:
+ (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "type" /* Type */:
+ (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
+ break;
+ case "lib" /* Lib */:
+ (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "prepend" /* Prepend */:
+ var prependNode = createUnparsedNode(section, node);
+ var prependTexts = void 0;
+ for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
+ var text = _c[_b];
+ if (!stripInternal || text.kind !== "internal" /* Internal */) {
+ (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
+ }
+ }
+ prependNode.texts = prependTexts || ts.emptyArray;
+ (texts || (texts = [])).push(prependNode);
+ break;
+ case "internal" /* Internal */:
+ if (stripInternal)
+ break;
+ // falls through
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.prologues = prologues || ts.emptyArray;
+ node.helpers = helpers;
+ node.referencedFiles = referencedFiles || ts.emptyArray;
+ node.typeReferenceDirectives = typeReferenceDirectives;
+ node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
+ node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
+ }
+ function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
+ ts.Debug.assert(!!node.oldFileOfCurrentEmit);
+ var texts;
+ var syntheticReferences;
+ for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "internal" /* Internal */:
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
+ break;
+ // Ignore
+ case "prologue" /* Prologue */:
+ case "emitHelpers" /* EmitHelpers */:
+ case "prepend" /* Prepend */:
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.texts = texts || ts.emptyArray;
+ node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
+ node.syntheticReferences = syntheticReferences;
+ return node;
+ }
+ function mapBundleFileSectionKindToSyntaxKind(kind) {
+ switch (kind) {
+ case "prologue" /* Prologue */: return 279 /* UnparsedPrologue */;
+ case "prepend" /* Prepend */: return 280 /* UnparsedPrepend */;
+ case "internal" /* Internal */: return 282 /* UnparsedInternalText */;
+ case "text" /* Text */: return 281 /* UnparsedText */;
+ case "emitHelpers" /* EmitHelpers */:
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
+ default:
+ return ts.Debug.assertNever(kind);
+ }
+ }
+ function createUnparsedNode(section, parent) {
+ var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ return node;
+ }
+ function createUnparsedSyntheticReference(section, parent) {
+ var node = ts.createNode(283 /* UnparsedSyntheticReference */, section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ node.section = section;
+ return node;
+ }
+ function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
+ var node = ts.createNode(287 /* InputFiles */);
if (!ts.isString(javascriptTextOrReadFileText)) {
var cache_1 = ts.createMap();
var textGetter_1 = function (path) {
@@ -61933,15 +62933,25 @@
var result = textGetter_1(path);
return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
};
+ var buildInfo_1;
+ var getAndCacheBuildInfo_1 = function (getText) {
+ if (buildInfo_1 === undefined) {
+ var result = getText();
+ buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
+ }
+ return buildInfo_1 || undefined;
+ };
node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath;
node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath;
+ node.buildInfoPath = declarationMapTextOrBuildInfoPath;
Object.defineProperties(node, {
javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
- declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } } // TODO:: if there is inline sourceMap in dtsFile, use that
+ declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
+ buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
});
}
else {
@@ -61950,7 +62960,12 @@
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
node.declarationText = declarationTextOrJavascriptPath;
node.declarationMapPath = declarationMapPath;
- node.declarationMapText = declarationMapText;
+ node.declarationMapText = declarationMapTextOrBuildInfoPath;
+ node.javascriptPath = javascriptPath;
+ node.declarationPath = declarationPath,
+ node.buildInfoPath = buildInfoPath;
+ node.buildInfo = buildInfo;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
}
return node;
}
@@ -62088,10 +63103,10 @@
// 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 === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return node.emitNode = { annotatedNodes: [node] };
}
- var sourceFile = ts.getSourceFileOfNode(node);
+ var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
}
node.emitNode = {};
@@ -62389,7 +63404,7 @@
ts.nullTransformationContext = {
enableEmitNotification: ts.noop,
enableSubstitution: ts.noop,
- endLexicalEnvironment: function () { return undefined; },
+ endLexicalEnvironment: ts.returnUndefined,
getCompilerOptions: ts.notImplemented,
getEmitHost: ts.notImplemented,
getEmitResolver: ts.notImplemented,
@@ -62534,38 +63549,38 @@
return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
}
ts.getHelperName = getHelperName;
- var valuesHelper = {
+ ts.valuesHelper = {
name: "typescript:values",
scoped: false,
text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };"
};
function createValuesHelper(context, expression, location) {
- context.requestEmitHelper(valuesHelper);
+ context.requestEmitHelper(ts.valuesHelper);
return ts.setTextRange(ts.createCall(getHelperName("__values"),
/*typeArguments*/ undefined, [expression]), location);
}
ts.createValuesHelper = createValuesHelper;
- var readHelper = {
+ ts.readHelper = {
name: "typescript:read",
scoped: false,
text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };"
};
function createReadHelper(context, iteratorRecord, count, location) {
- context.requestEmitHelper(readHelper);
+ context.requestEmitHelper(ts.readHelper);
return ts.setTextRange(ts.createCall(getHelperName("__read"),
/*typeArguments*/ undefined, count !== undefined
? [iteratorRecord, ts.createLiteral(count)]
: [iteratorRecord]), location);
}
ts.createReadHelper = createReadHelper;
- var spreadHelper = {
+ ts.spreadHelper = {
name: "typescript:spread",
scoped: false,
text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
};
function createSpreadHelper(context, argumentList, location) {
- context.requestEmitHelper(readHelper);
- context.requestEmitHelper(spreadHelper);
+ context.requestEmitHelper(ts.readHelper);
+ context.requestEmitHelper(ts.spreadHelper);
return ts.setTextRange(ts.createCall(getHelperName("__spread"),
/*typeArguments*/ undefined, argumentList), location);
}
@@ -62736,7 +63751,7 @@
function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) {
var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
if (property === firstAccessor) {
- var properties_8 = [];
+ var properties_7 = [];
if (getAccessor) {
var getterFunction = ts.createFunctionExpression(getAccessor.modifiers,
/*asteriskToken*/ undefined,
@@ -62747,7 +63762,7 @@
ts.setTextRange(getterFunction, getAccessor);
ts.setOriginalNode(getterFunction, getAccessor);
var getter = ts.createPropertyAssignment("get", getterFunction);
- properties_8.push(getter);
+ properties_7.push(getter);
}
if (setAccessor) {
var setterFunction = ts.createFunctionExpression(setAccessor.modifiers,
@@ -62759,15 +63774,15 @@
ts.setTextRange(setterFunction, setAccessor);
ts.setOriginalNode(setterFunction, setAccessor);
var setter = ts.createPropertyAssignment("set", setterFunction);
- properties_8.push(setter);
+ properties_7.push(setter);
}
- properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
- properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
+ properties_7.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
+ properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"),
/*typeArguments*/ undefined, [
receiver,
createExpressionForPropertyName(property.name),
- ts.createObjectLiteral(properties_8, multiLine)
+ ts.createObjectLiteral(properties_7, multiLine)
]),
/*location*/ firstAccessor);
return ts.aggregateTransformFlags(expression);
@@ -63411,7 +64426,7 @@
case 190 /* ElementAccessExpression */:
case 189 /* PropertyAccessExpression */:
case 213 /* NonNullExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -63427,7 +64442,7 @@
ts.parenthesizeConciseBody = parenthesizeConciseBody;
function isCommaSequence(node) {
return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
- node.kind === 309 /* CommaListExpression */;
+ node.kind === 314 /* CommaListExpression */;
}
ts.isCommaSequence = isCommaSequence;
var OuterExpressionKinds;
@@ -63446,7 +64461,7 @@
case 212 /* AsExpression */:
case 213 /* NonNullExpression */:
return (kinds & 2 /* Assertions */) !== 0;
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
}
return false;
@@ -63483,7 +64498,7 @@
case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
- case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 313 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
/**
@@ -64275,12 +65290,12 @@
case 278 /* EnumMember */:
return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
// No need to visit nodes with no children.
@@ -64336,7 +65351,7 @@
case 220 /* EmptyStatement */:
case 210 /* OmittedExpression */:
case 236 /* DebuggerStatement */:
- case 307 /* NotEmittedStatement */:
+ case 312 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
@@ -64713,14 +65728,14 @@
result = reduceNode(node.initializer, cbNode, result);
break;
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
result = reduceNodes(node.statements, cbNodes, result);
break;
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -64734,8 +65749,8 @@
return statements;
}
return ts.isNodeArray(statements)
- ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements)
- : ts.addStatementsAfterPrologue(statements, declarations);
+ ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements)
+ : ts.insertStatementsAfterStandardPrologue(statements, declarations);
}
ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
/**
@@ -65001,7 +66016,7 @@
}
exit();
}
- function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) {
+ function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
var _a;
ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
@@ -65011,6 +66026,14 @@
var nameIndexToNewNameIndexMap;
var mappingIterator = decodeMappings(map.mappings);
for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) {
+ if (end && (raw.generatedLine > end.line ||
+ (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
+ break;
+ }
+ if (start && (raw.generatedLine < start.line ||
+ (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
+ continue;
+ }
// Then reencode all the updated mappings into the overall map
var newSourceIndex = void 0;
var newSourceLine = void 0;
@@ -65039,8 +66062,10 @@
}
}
}
- var newGeneratedLine = raw.generatedLine + generatedLine;
- var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter;
+ var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
+ var newGeneratedLine = rawGeneratedLine + generatedLine;
+ var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
+ var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
}
exit();
@@ -65523,7 +66548,7 @@
function chainBundle(transformSourceFile) {
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
+ return node.kind === 284 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
}
function transformBundle(node) {
return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
@@ -65999,8 +67024,8 @@
if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
if (flattenContext.level >= 1 /* ObjectRest */
- && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */))
- && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */))
+ && !(element.transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */))
+ && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */))
&& !ts.isComputedPropertyName(propertyName)) {
bindingElements = ts.append(bindingElements, element);
}
@@ -66066,7 +67091,7 @@
if (flattenContext.level >= 1 /* ObjectRest */) {
// If an array pattern contains an ObjectRest, we must cache the result so that we
// can perform the ObjectRest destructuring in a different declaration
- if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (element.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
if (flattenContext.hoistTempVariables) {
flattenContext.context.hoistVariableDeclaration(temp);
@@ -66184,7 +67209,7 @@
function makeAssignmentElement(name) {
return name;
}
- var restHelper = {
+ ts.restHelper = {
name: "typescript:rest",
scoped: false,
text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
@@ -66193,7 +67218,7 @@
* `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
*/
function createRestCall(context, value, elements, computedTempVariables, location) {
- context.requestEmitHelper(restHelper);
+ context.requestEmitHelper(ts.restHelper);
var propertyNames = [];
var computedTempVariableOffset = 0;
for (var i = 0; i < elements.length - 1; i++) {
@@ -66294,14 +67319,14 @@
var pendingExpressions;
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* 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 === 282 /* InputFiles */) {
+ if (prepend.kind === 287 /* InputFiles */) {
return ts.createUnparsedSourceFile(prepend, "js");
}
return prepend;
@@ -66350,7 +67375,7 @@
*/
function onBeforeVisitNode(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 245 /* ModuleBlock */:
case 218 /* Block */:
@@ -66394,14 +67419,9 @@
* @param node The node to visit.
*/
function visitorWorker(node) {
- if (node.transformFlags & 1 /* TypeScript */) {
- // This node is explicitly marked as TypeScript, so we should transform the node.
+ if (node.transformFlags & 1 /* ContainsTypeScript */) {
return visitTypeScript(node);
}
- else if (node.transformFlags & 2 /* ContainsTypeScript */) {
- // This node contains TypeScript, so we should visit its children.
- return ts.visitEachChild(node, visitor, context);
- }
return node;
}
/**
@@ -66435,7 +67455,7 @@
// As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
// We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
// and will trigger debug failures when debug verbosity is turned up
- if (node.transformFlags & 2 /* ContainsTypeScript */) {
+ if (node.transformFlags & 1 /* ContainsTypeScript */) {
// This node contains TypeScript, so we should visit its children.
return ts.visitEachChild(node, visitor, context);
}
@@ -66477,15 +67497,9 @@
// do not emit ES6 imports and exports since they are illegal inside a namespace
return undefined;
}
- else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
- // This node is explicitly marked as TypeScript, or is exported at the namespace
- // level, so we should transform the node.
+ else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
return visitTypeScript(node);
}
- else if (node.transformFlags & 2 /* ContainsTypeScript */) {
- // This node contains TypeScript, so we should visit its children.
- return ts.visitEachChild(node, visitor, context);
- }
return node;
}
/**
@@ -66536,7 +67550,7 @@
* @param node The node to visit.
*/
function visitTypeScript(node) {
- if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) {
+ if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) {
// TypeScript ambient declarations are elided, but some comments may be preserved.
// See the implementation of `getLeadingComments` in comments.ts for more details.
return ts.createNotEmittedStatement(node);
@@ -66603,7 +67617,7 @@
// See the implementation of `getLeadingComments` in comments.ts for more details.
return ts.createNotEmittedStatement(node);
case 240 /* ClassDeclaration */:
- // This is a class declaration with TypeScript syntax extensions.
+ // This may be a class declaration with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
// - decorators
@@ -66614,7 +67628,7 @@
// - method overload signatures
return visitClassDeclaration(node);
case 209 /* ClassExpression */:
- // This is a class expression with TypeScript syntax extensions.
+ // This may be a class expression with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
// - decorators
@@ -66625,7 +67639,7 @@
// - method overload signatures
return visitClassExpression(node);
case 273 /* HeritageClause */:
- // This is a heritage clause with TypeScript syntax extensions.
+ // This may be a heritage clause with TypeScript syntax extensions.
//
// TypeScript heritage clause extensions include:
// - `implements` clause
@@ -66653,7 +67667,7 @@
// TypeScript arrow functions can have modifiers and type annotations.
return visitArrowFunction(node);
case 151 /* Parameter */:
- // This is a parameter declaration with TypeScript syntax extensions.
+ // This may be a parameter declaration with TypeScript syntax extensions.
//
// TypeScript parameter declaration syntax extensions include:
// - decorators
@@ -66694,7 +67708,8 @@
// TypeScript namespace or external module import.
return visitImportEqualsDeclaration(node);
default:
- return ts.Debug.failBadSyntaxKind(node);
+ // node contains some other TypeScript syntax
+ return ts.visitEachChild(node, visitor, context);
}
}
function visitSourceFile(node) {
@@ -66743,18 +67758,19 @@
facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
return facts;
}
- /**
- * Transforms a class declaration with TypeScript syntax into compatible ES6.
- *
- * This function will only be called when one of the following conditions are met:
- * - The class has decorators.
- * - The class has property declarations with initializers.
- * - The class contains a constructor that contains parameters with accessibility modifiers.
- * - The class is an export in a TypeScript namespace.
- *
- * @param node The node to transform.
- */
+ function hasTypeScriptClassSyntax(node) {
+ return !!(node.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */);
+ }
+ function isClassLikeDeclarationWithTypeScriptSyntax(node) {
+ return ts.some(node.decorators)
+ || ts.some(node.typeParameters)
+ || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
+ || ts.some(node.members, hasTypeScriptClassSyntax);
+ }
function visitClassDeclaration(node) {
+ if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) {
+ return ts.visitEachChild(node, visitor, context);
+ }
var savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
@@ -66807,7 +67823,7 @@
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
var iife = ts.createImmediatelyInvokedArrowFunction(statements);
ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
var varStatement = ts.createVariableStatement(
@@ -66984,16 +68000,10 @@
ts.setCommentRange(statement, node);
return statement;
}
- /**
- * Transforms a class expression with TypeScript syntax into compatible ES6.
- *
- * This function will only be called when one of the following conditions are met:
- * - The class has property declarations with initializers.
- * - The class contains a constructor that contains parameters with accessibility modifiers.
- *
- * @param node The node to transform.
- */
function visitClassExpression(node) {
+ if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
+ return ts.visitEachChild(node, visitor, context);
+ }
var savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
@@ -67057,7 +68067,7 @@
var constructor = ts.getFirstConstructorWithBody(node);
var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty);
var hasParameterPropertyAssignments = constructor &&
- constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ &&
+ constructor.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */ &&
ts.forEach(constructor.parameters, isParameterWithPropertyAssignment);
// If the class does not contain nodes that require a synthesized constructor,
// accept the current constructor if it exists.
@@ -67256,8 +68266,8 @@
* @param receiver The receiver on which each property should be assigned.
*/
function addInitializedPropertyStatements(statements, properties, receiver) {
- for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
- var property = properties_9[_i];
+ for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
+ var property = properties_8[_i];
var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver));
ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
ts.setCommentRange(statement, property);
@@ -67273,8 +68283,8 @@
*/
function generateInitializedPropertyExpressions(properties, receiver) {
var expressions = [];
- for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) {
- var property = properties_10[_i];
+ for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
+ var property = properties_9[_i];
var expression = transformInitializedProperty(property, receiver);
ts.startOnNewLine(expression);
ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
@@ -67348,11 +68358,14 @@
var decorators;
if (node) {
var parameters = node.parameters;
- for (var i = 0; i < parameters.length; i++) {
- var parameter = parameters[i];
+ var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
+ var firstParameterOffset = firstParameterIsThis ? 1 : 0;
+ var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
+ for (var i = 0; i < numParameters; i++) {
+ var parameter = parameters[i + firstParameterOffset];
if (decorators || parameter.decorators) {
if (!decorators) {
- decorators = new Array(parameters.length);
+ decorators = new Array(numParameters);
}
decorators[i] = parameter.decorators;
}
@@ -67852,8 +68865,12 @@
return serializeTypeList(node.types);
case 175 /* ConditionalType */:
return serializeTypeList([node.trueType, node.falseType]);
- case 167 /* TypeQuery */:
case 179 /* TypeOperator */:
+ if (node.operator === 133 /* ReadonlyKeyword */) {
+ return serializeTypeNode(node.type);
+ }
+ break;
+ case 167 /* TypeQuery */:
case 180 /* IndexedAccessType */:
case 181 /* MappedType */:
case 168 /* TypeLiteral */:
@@ -67871,8 +68888,8 @@
// Note when updating logic here also update getEntityNameForDecoratorMetadata
// so that aliases can be marked as referenced
var serializedUnion;
- for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
- var typeNode = types_17[_i];
+ for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
+ var typeNode = types_18[_i];
while (typeNode.kind === 177 /* ParenthesizedType */) {
typeNode = typeNode.type; // Skip parens if need be
}
@@ -68014,7 +69031,7 @@
* available.
*/
function getGlobalBigIntNameWithFallback() {
- return languageVersion < 6 /* ESNext */
+ return languageVersion < 7 /* ESNext */
? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object"))
: ts.createIdentifier("BigInt");
}
@@ -68098,12 +69115,12 @@
* @param node The HeritageClause to transform.
*/
function visitHeritageClause(node) {
- if (node.token === 86 /* ExtendsKeyword */) {
- var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1);
- return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node);
- }
+ if (node.token === 109 /* ImplementsKeyword */) {
+ // implements clauses are elided
return undefined;
}
+ return ts.visitEachChild(node, visitor, context);
+ }
/**
* Transforms an ExpressionWithTypeArguments with TypeScript syntax.
*
@@ -68138,16 +69155,6 @@
}
return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context));
}
- /**
- * Visits a method declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is an overload
- * - The node is marked as abstract, public, private, protected, or readonly
- * - The node has a computed property name
- *
- * @param node The method node.
- */
function visitMethodDeclaration(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return undefined;
@@ -68174,15 +69181,6 @@
function shouldEmitAccessorDeclaration(node) {
return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));
}
- /**
- * Visits a get accessor declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked as abstract, public, private, or protected
- * - The node has a computed property name
- *
- * @param node The get accessor node.
- */
function visitGetAccessor(node) {
if (!shouldEmitAccessorDeclaration(node)) {
return undefined;
@@ -68198,15 +69196,6 @@
}
return updated;
}
- /**
- * Visits a set accessor declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked as abstract, public, private, or protected
- * - The node has a computed property name
- *
- * @param node The set accessor node.
- */
function visitSetAccessor(node) {
if (!shouldEmitAccessorDeclaration(node)) {
return undefined;
@@ -68221,16 +69210,6 @@
}
return updated;
}
- /**
- * Visits a function declaration.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is an overload
- * - The node is exported from a TypeScript namespace
- * - The node has decorators
- *
- * @param node The function node.
- */
function visitFunctionDeclaration(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return ts.createNotEmittedStatement(node);
@@ -68246,14 +69225,6 @@
}
return updated;
}
- /**
- * Visits a function expression node.
- *
- * This function will be called when one of the following conditions are met:
- * - The node has type annotations
- *
- * @param node The function expression node.
- */
function visitFunctionExpression(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return ts.createOmittedExpression();
@@ -68263,51 +69234,31 @@
/*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
return updated;
}
- /**
- * @remarks
- * This function will be called when one of the following conditions are met:
- * - The node has type annotations
- */
function visitArrowFunction(node) {
var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier),
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
/*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
return updated;
}
- /**
- * Visits a parameter declaration node.
- *
- * This function will be called when one of the following conditions are met:
- * - The node has an accessibility modifier.
- * - The node has a questionToken.
- * - The node's kind is ThisKeyword.
- *
- * @param node The parameter declaration node.
- */
function visitParameter(node) {
if (ts.parameterIsThisKeyword(node)) {
return undefined;
}
- var parameter = ts.createParameter(
+ var updated = ts.updateParameter(node,
/*decorators*/ undefined,
/*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName),
/*questionToken*/ undefined,
/*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
+ if (updated !== node) {
// While we emit the source map for the node after skipping decorators and modifiers,
// we need to emit the comments for the original range.
- ts.setOriginalNode(parameter, node);
- ts.setTextRange(parameter, ts.moveRangePastModifiers(node));
- ts.setCommentRange(parameter, node);
- ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node));
- ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */);
- return parameter;
+ ts.setCommentRange(updated, node);
+ ts.setTextRange(updated, ts.moveRangePastModifiers(node));
+ ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
+ ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
+ }
+ return updated;
}
- /**
- * Visits a variable statement in a namespace.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is exported from a TypeScript namespace.
- */
function visitVariableStatement(node) {
if (isExportOfNamespace(node)) {
var variables = ts.getInitializedVariables(node.declarationList);
@@ -68336,12 +69287,6 @@
return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName),
/*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
}
- /**
- * Visits a parenthesized expression that contains either a type assertion or an `as`
- * expression.
- *
- * @param node The parenthesized expression node.
- */
function visitParenthesizedExpression(node) {
var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */);
if (ts.isAssertionExpression(innerExpression)) {
@@ -68478,7 +69423,7 @@
var statements = [];
startLexicalEnvironment();
var members = ts.map(node.members, transformEnumMember);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
ts.addRange(statements, members);
currentNamespaceContainerName = savedCurrentNamespaceLocalName;
return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members),
@@ -68577,7 +69522,7 @@
// 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))
- ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
+ ], currentLexicalScope.kind === 284 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
ts.setOriginalNode(statement, node);
recordEmittedDeclarationInScope(node);
if (isFirstEmittedDeclarationInScope(node)) {
@@ -68725,7 +69670,7 @@
var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
currentNamespaceContainerName = savedCurrentNamespaceContainerName;
currentNamespace = savedCurrentNamespace;
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
@@ -69142,7 +70087,7 @@
// 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 !== 279 /* SourceFile */) {
+ if (container && container.kind !== 284 /* SourceFile */) {
var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) ||
(applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */);
if (substitute) {
@@ -69193,39 +70138,39 @@
argumentsArray.push(descriptor);
}
}
- context.requestEmitHelper(decorateHelper);
+ context.requestEmitHelper(ts.decorateHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"),
/*typeArguments*/ undefined, argumentsArray), location);
}
- var decorateHelper = {
+ ts.decorateHelper = {
name: "typescript:decorate",
scoped: false,
priority: 2,
text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
};
function createMetadataHelper(context, metadataKey, metadataValue) {
- context.requestEmitHelper(metadataHelper);
+ context.requestEmitHelper(ts.metadataHelper);
return ts.createCall(ts.getHelperName("__metadata"),
/*typeArguments*/ undefined, [
ts.createLiteral(metadataKey),
metadataValue
]);
}
- var metadataHelper = {
+ ts.metadataHelper = {
name: "typescript:metadata",
scoped: false,
priority: 3,
text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
};
function createParamHelper(context, expression, parameterOffset, location) {
- context.requestEmitHelper(paramHelper);
+ context.requestEmitHelper(ts.paramHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__param"),
/*typeArguments*/ undefined, [
ts.createLiteral(parameterOffset),
expression
]), location);
}
- var paramHelper = {
+ ts.paramHelper = {
name: "typescript:param",
scoped: false,
priority: 4,
@@ -69280,7 +70225,7 @@
return visited;
}
function visitor(node) {
- if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) {
+ if ((node.transformFlags & 32 /* ContainsES2017 */) === 0) {
return node;
}
switch (node.kind) {
@@ -69550,22 +70495,26 @@
}
var savedCapturedSuperProperties = capturedSuperProperties;
var savedHasSuperElementAccess = hasSuperElementAccess;
+ if (!isArrowFunction) {
capturedSuperProperties = ts.createUnderscoreEscapedMap();
hasSuperElementAccess = false;
+ }
var result;
if (!isArrowFunction) {
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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
if (emitSuperHelpers) {
enableSubstitutionForAsyncMethodsWithSuper();
+ if (ts.hasEntries(capturedSuperProperties)) {
var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
- ts.addStatementsAfterPrologue(statements, [variableStatement]);
+ ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
+ }
}
var block = ts.createBlock(statements, /*multiLine*/ true);
ts.setTextRange(block, node.body);
@@ -69592,8 +70541,10 @@
}
}
enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
+ if (!isArrowFunction) {
capturedSuperProperties = savedCapturedSuperProperties;
hasSuperElementAccess = savedHasSuperElementAccess;
+ }
return result;
}
function transformAsyncFunctionBodyWorker(body, start) {
@@ -69746,7 +70697,7 @@
/* typeParameters */ undefined,
/* parameters */ [],
/* type */ undefined,
- /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name))));
+ /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
if (hasBinding) {
getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(
/* modifiers */ undefined,
@@ -69761,7 +70712,7 @@
/* initializer */ undefined)
],
/* type */ undefined,
- /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v")))));
+ /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v")))));
}
accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter)));
});
@@ -69776,14 +70727,14 @@
], 2 /* Const */));
}
ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
- var awaiterHelper = {
+ ts.awaiterHelper = {
name: "typescript:awaiter",
scoped: false,
priority: 5,
text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
};
function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
- context.requestEmitHelper(awaiterHelper);
+ context.requestEmitHelper(ts.awaiterHelper);
var generatorFunc = ts.createFunctionExpression(
/*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */),
/*name*/ undefined,
@@ -69819,7 +70770,7 @@
/** Enables substitutions for async methods with `super` calls. */
ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
})(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
- function transformESNext(context) {
+ function transformES2018(context) {
var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
var resolver = context.getEmitResolver();
var compilerOptions = context.getCompilerOptions();
@@ -69859,7 +70810,7 @@
return node;
}
function visitorWorker(node, noDestructuringValue) {
- if ((node.transformFlags & 8 /* ContainsESNext */) === 0) {
+ if ((node.transformFlags & 16 /* ContainsES2018 */) === 0) {
return node;
}
switch (node.kind) {
@@ -69903,8 +70854,6 @@
return visitExpressionStatement(node);
case 195 /* ParenthesizedExpression */:
return visitParenthesizedExpression(node, noDestructuringValue);
- case 274 /* CatchClause */:
- return visitCatchClause(node);
case 189 /* PropertyAccessExpression */:
if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) {
capturedSuperProperties.set(node.name.escapedText, true);
@@ -69979,7 +70928,7 @@
return objects;
}
function visitObjectLiteralExpression(node) {
- if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
// spread elements emit like so:
// non-spread elements are chunked together into object literals, and then all are passed to __assign:
// { a, ...o, b } => __assign({a}, o, {b});
@@ -69999,19 +70948,13 @@
function visitParenthesizedExpression(node, noDestructuringValue) {
return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
}
- function visitCatchClause(node) {
- if (!node.variableDeclaration) {
- return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
- }
- return ts.visitEachChild(node, visitor, context);
- }
/**
* Visits a BinaryExpression that contains a destructuring assignment.
*
* @param node A BinaryExpression node.
*/
function visitBinaryExpression(node, noDestructuringValue) {
- if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
}
else if (node.operatorToken.kind === 27 /* CommaToken */) {
@@ -70026,7 +70969,7 @@
*/
function visitVariableDeclaration(node) {
// If we are here it is because the name contains a binding pattern with a rest somewhere in it.
- if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (ts.isBindingPattern(node.name) && node.name.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */);
}
return ts.visitEachChild(node, visitor, context);
@@ -70043,7 +70986,7 @@
* @param node A ForOfStatement.
*/
function visitForOfStatement(node, outermostLabeledStatement) {
- if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.initializer.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
node = transformForOfStatementWithObjectRest(node);
}
if (node.awaitModifier) {
@@ -70140,7 +71083,7 @@
]));
}
function visitParameter(node) {
- if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
// Binding patterns are converted into a generated name and are
// evaluated inside the function body.
return ts.updateParameter(node,
@@ -70253,10 +71196,10 @@
enableSubstitutionForAsyncMethodsWithSuper();
var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
- ts.addStatementsAfterPrologue(statements, [variableStatement]);
+ ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
}
statements.push(returnStatement);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var block = ts.updateBlock(node.body, statements);
if (emitSuperHelpers && hasSuperElementAccess) {
if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
@@ -70282,7 +71225,7 @@
var leadingStatements = endLexicalEnvironment();
if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
- ts.addStatementsAfterPrologue(statements, leadingStatements);
+ ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
ts.addRange(statements, block.statements.slice(statementOffset));
return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
}
@@ -70291,7 +71234,7 @@
function appendObjectRestAssignmentsIfNeeded(statements, node) {
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
- if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (parameter.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
var temp = ts.getGeneratedNameForNode(parameter);
var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp,
/*doNotRecordTempVariablesInLine*/ false,
@@ -70422,8 +71365,8 @@
}
}
}
- ts.transformESNext = transformESNext;
- var assignHelper = {
+ ts.transformES2018 = transformES2018;
+ ts.assignHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
@@ -70434,28 +71377,28 @@
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"),
/*typeArguments*/ undefined, attributesSegments);
}
- context.requestEmitHelper(assignHelper);
+ context.requestEmitHelper(ts.assignHelper);
return ts.createCall(ts.getHelperName("__assign"),
/*typeArguments*/ undefined, attributesSegments);
}
ts.createAssignHelper = createAssignHelper;
- var awaitHelper = {
+ ts.awaitHelper = {
name: "typescript:await",
scoped: false,
text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
};
function createAwaitHelper(context, expression) {
- context.requestEmitHelper(awaitHelper);
+ context.requestEmitHelper(ts.awaitHelper);
return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
}
- var asyncGeneratorHelper = {
+ ts.asyncGeneratorHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
};
function createAsyncGeneratorHelper(context, generatorFunc) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncGeneratorHelper);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncGeneratorHelper);
// Mark this node as originally an async function
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */;
return ts.createCall(ts.getHelperName("__asyncGenerator"),
@@ -70465,24 +71408,24 @@
generatorFunc
]);
}
- var asyncDelegator = {
+ ts.asyncDelegator = {
name: "typescript:asyncDelegator",
scoped: false,
text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
};
function createAsyncDelegatorHelper(context, expression, location) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncDelegator);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncDelegator);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"),
/*typeArguments*/ undefined, [expression]), location);
}
- var asyncValues = {
+ ts.asyncValues = {
name: "typescript:asyncValues",
scoped: false,
text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
};
function createAsyncValuesHelper(context, expression, location) {
- context.requestEmitHelper(asyncValues);
+ context.requestEmitHelper(ts.asyncValues);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"),
/*typeArguments*/ undefined, [expression]), location);
}
@@ -70490,6 +71433,60 @@
/*@internal*/
var ts;
(function (ts) {
+ function transformES2019(context) {
+ return ts.chainBundle(transformSourceFile);
+ function transformSourceFile(node) {
+ if (node.isDeclarationFile) {
+ return node;
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitor(node) {
+ if ((node.transformFlags & 8 /* ContainsES2019 */) === 0) {
+ return node;
+ }
+ switch (node.kind) {
+ case 274 /* CatchClause */:
+ return visitCatchClause(node);
+ default:
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ function visitCatchClause(node) {
+ if (!node.variableDeclaration) {
+ return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ ts.transformES2019 = transformES2019;
+})(ts || (ts = {}));
+/*@internal*/
+var ts;
+(function (ts) {
+ function transformESNext(context) {
+ return ts.chainBundle(transformSourceFile);
+ function transformSourceFile(node) {
+ if (node.isDeclarationFile) {
+ return node;
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitor(node) {
+ if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
+ return node;
+ }
+ switch (node.kind) {
+ default:
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ }
+ ts.transformESNext = transformESNext;
+})(ts || (ts = {}));
+/*@internal*/
+var ts;
+(function (ts) {
function transformJsx(context) {
var compilerOptions = context.getCompilerOptions();
var currentSourceFile;
@@ -70509,7 +71506,7 @@
return visited;
}
function visitor(node) {
- if (node.transformFlags & 4 /* ContainsJsx */) {
+ if (node.transformFlags & 2 /* ContainsJsx */) {
return visitorWorker(node);
}
else {
@@ -70626,7 +71623,7 @@
}
}
function visitJsxText(node) {
- var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, /*includeTrivia*/ true));
+ var fixed = fixupWhitespaceAndDecodeEntities(node.text);
return fixed === undefined ? undefined : ts.createLiteral(fixed);
}
/**
@@ -71011,7 +72008,7 @@
return ts.visitEachChild(node, visitor, context);
}
function visitor(node) {
- if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) {
+ if ((node.transformFlags & 64 /* ContainsES2016 */) === 0) {
return node;
}
switch (node.kind) {
@@ -71091,30 +72088,6 @@
Jump[Jump["Continue"] = 4] = "Continue";
Jump[Jump["Return"] = 8] = "Return";
})(Jump || (Jump = {}));
- var SuperCaptureResult;
- (function (SuperCaptureResult) {
- /**
- * A capture may have been added for calls to 'super', but
- * the caller should emit subsequent statements normally.
- */
- SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement";
- /**
- * A call to 'super()' got replaced with a capturing statement like:
- *
- * var _this = _super.call(...) || this;
- *
- * Callers should skip the current statement.
- */
- SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture";
- /**
- * A call to 'super()' got replaced with a capturing statement like:
- *
- * return _super.call(...) || this;
- *
- * Callers should skip the current statement and avoid any returns of '_this'.
- */
- SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn";
- })(SuperCaptureResult || (SuperCaptureResult = {}));
// Facts we track as we traverse the tree
var HierarchyFacts;
(function (HierarchyFacts) {
@@ -71135,12 +72108,12 @@
HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement";
HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement";
HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper";
- HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName";
// NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
+ // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
//
// Ancestor masks
//
- HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
+ HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 8191] = "AncestorFactsMask";
// We are always in *some* kind of block scope, but only specific block-scope containers are
// top-level or Blocks.
HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
@@ -71150,16 +72123,16 @@
HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes";
// Functions, methods, and accessors are both new lexical scopes and new block scopes.
HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
- HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
+ HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 8094] = "FunctionExcludes";
HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
- HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
+ HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 8086] = "AsyncFunctionBodyExcludes";
// Arrow functions are lexically scoped to their container, but are new block scopes.
HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
- HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes";
+ HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 8064] = "ArrowFunctionExcludes";
// Constructors are both new lexical scopes and new block scopes. Constructors are also
// always considered non-static members of a class.
HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
- HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
+ HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 8086] = "ConstructorExcludes";
// 'do' and 'while' statements are not block scopes. We track that the subtree is contained
// within an IterationStatement to indicate whether the embedded statement is an
// IterationStatementBlock.
@@ -71177,19 +72150,17 @@
HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes";
HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes";
- // Computed property names track subtree flags differently than their containing members.
- HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes";
- HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes";
//
// Subtree facts
//
- HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
- HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName";
+ HierarchyFacts[HierarchyFacts["NewTarget"] = 8192] = "NewTarget";
+ HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 16384] = "CapturedLexicalThis";
//
// Subtree masks
//
- HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
- HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask";
+ HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -8192] = "SubtreeFactsMask";
+ HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
+ HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 24576] = "FunctionSubtreeExcludes";
})(HierarchyFacts || (HierarchyFacts = {}));
function transformES2015(context) {
var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
@@ -71238,7 +72209,7 @@
*/
function enterSubtree(excludeFacts, includeFacts) {
var ancestorFacts = hierarchyFacts;
- hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 8191 /* AncestorFactsMask */;
return ancestorFacts;
}
/**
@@ -71249,7 +72220,7 @@
* @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
*/
function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
- hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -8192 /* SubtreeFactsMask */ | ancestorFacts;
}
function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0
@@ -71271,12 +72242,6 @@
return node;
}
}
- function functionBodyVisitor(node) {
- if (shouldVisitNode(node)) {
- return visitBlock(node, /*isFunctionBody*/ true);
- }
- return node;
- }
function callExpressionVisitor(node) {
if (node.kind === 98 /* SuperKeyword */) {
return visitSuperKeyword(/*isExpressionOfCall*/ true);
@@ -71383,18 +72348,19 @@
}
function visitSourceFile(node) {
var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
+ var prologue = [];
var statements = [];
startLexicalEnvironment();
- var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false);
- addCaptureThisForNodeIfNeeded(statements, node);
- statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor);
+ var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false);
+ statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor);
ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
if (taggedTemplateStringDeclarations) {
statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureThisForNodeIfNeeded(prologue, node);
exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
- return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
+ return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
}
function visitSwitchStatement(node) {
if (convertedLoopState !== undefined) {
@@ -71434,6 +72400,9 @@
return ts.visitEachChild(node, visitor, context);
}
function visitThisKeyword(node) {
+ if (hierarchyFacts & 2 /* ArrowFunction */) {
+ hierarchyFacts |= 16384 /* CapturedLexicalThis */;
+ }
if (convertedLoopState) {
if (hierarchyFacts & 2 /* ArrowFunction */) {
// if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
@@ -71647,7 +72616,7 @@
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
ts.setEmitFlags(block, 1536 /* NoComments */);
return block;
@@ -71675,7 +72644,7 @@
function addConstructor(statements, node, extendsClauseElement) {
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
+ var ancestorFacts = enterSubtree(8086 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
var constructor = ts.getFirstConstructorWithBody(node);
var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
var constructorFunction = ts.createFunctionDeclaration(
@@ -71689,7 +72658,7 @@
ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
}
statements.push(constructorFunction);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
}
/**
@@ -71708,6 +72677,24 @@
return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
|| [];
}
+ function createDefaultConstructorBody(node, isDerivedClass) {
+ // We must be here because the user didn't write a constructor
+ // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
+ // If that's the case we can just immediately return the result of a 'super()' call.
+ var statements = [];
+ resumeLexicalEnvironment();
+ ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
+ if (isDerivedClass) {
+ // return _super !== null && _super.apply(this, arguments) || this;
+ statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
+ }
+ var statementsArray = ts.createNodeArray(statements);
+ ts.setTextRange(statementsArray, node.members);
+ var block = ts.createBlock(statementsArray, /*multiLine*/ true);
+ ts.setTextRange(block, node);
+ ts.setEmitFlags(block, 1536 /* NoComments */);
+ return block;
+ }
/**
* Transforms the body of a constructor declaration of a class.
*
@@ -71718,59 +72705,137 @@
* synthesized `super` call.
*/
function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
+ // determine whether the class is known syntactically to be a derived class (e.g. a
+ // class that extends a value that is not syntactically known to be `null`).
+ var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */;
+ // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
+ // representation:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base { }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // return _super.apply(this, arguments) || this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ if (!constructor)
+ return createDefaultConstructorBody(node, isDerivedClass);
+ // The prologue will contain all leading standard and custom prologue statements added by this transform
+ var prologue = [];
var statements = [];
resumeLexicalEnvironment();
- var statementOffset = -1;
- if (hasSynthesizedSuper) {
// If a super call has already been synthesized,
// we're going to assume that we should just transform everything after that.
// The assumption is that no prior step in the pipeline has added any prologue directives.
- statementOffset = 0;
- }
- else if (constructor) {
- statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false);
- }
- if (constructor) {
+ var statementOffset = 0;
+ if (!hasSynthesizedSuper)
+ statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false);
addDefaultValueAssignmentsIfNeeded(statements, constructor);
addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
- if (!hasSynthesizedSuper) {
- // If no super call has been synthesized, emit custom prologue directives.
+ if (!hasSynthesizedSuper)
statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
+ // If the first statement is a call to `super()`, visit the statement directly
+ var superCallExpression;
+ if (hasSynthesizedSuper) {
+ superCallExpression = createDefaultSuperCallOrThis();
}
- ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!");
+ else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
+ var firstStatement = constructor.body.statements[statementOffset];
+ if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
+ superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
}
- // determine whether the class is known syntactically to be a derived class (e.g. a
- // class that extends a value that is not syntactically known to be `null`).
- var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */;
- var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset);
- // The last statement expression was replaced. Skip it.
- if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) {
- statementOffset++;
}
- if (constructor) {
- if (superCaptureStatus === 1 /* ReplaceSuperCapture */) {
+ if (superCallExpression) {
hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */;
+ statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
}
+ // visit the remaining statements
ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
+ if (isDerivedClass) {
+ if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 2048 /* ContainsLexicalThis */)) {
+ // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
+ // following representation:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base {
+ // constructor() {
+ // super("foo");
+ // }
+ // }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // return _super.call(this, "foo") || this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
+ var returnStatement = ts.createReturn(superCallExpression);
+ ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
+ ts.setEmitFlags(superCall, 1536 /* NoComments */);
+ statements.push(returnStatement);
}
- // Return `_this` unless we're sure enough that it would be pointless to add a return statement.
- // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return.
- if (isDerivedClass
- && superCaptureStatus !== 2 /* ReplaceWithReturn */
- && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) {
+ else {
+ // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base {
+ // constructor() {
+ // super("foo");
+ // this.x = 1;
+ // }
+ // }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // var _this = _super.call(this, "foo") || this;
+ // _this.x = 1;
+ // return _this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ // Since the `super()` call was the first statement, we insert the `this` capturing call to
+ // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
+ insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
+ if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
- if (constructor) {
- prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false);
}
- var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements),
- /*location*/ constructor ? constructor.body.statements : node.members),
- /*multiLine*/ true);
- ts.setTextRange(block, constructor ? constructor.body : node);
- if (!constructor) {
- ts.setEmitFlags(block, 1536 /* NoComments */);
}
+ else {
+ // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
+ // captured when necessitated by an arrow function capturing the lexical `this`:
+ //
+ // ```
+ // // es2015
+ // class C {}
+ //
+ // // es5
+ // var C = (function () {
+ // function C() {
+ // }
+ // return C;
+ // })();
+ // ```
+ insertCaptureThisForNodeIfNeeded(prologue, constructor);
+ }
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)),
+ /*location*/ constructor.body.statements),
+ /*multiLine*/ true);
+ ts.setTextRange(block, constructor.body);
return block;
}
/**
@@ -71800,83 +72865,6 @@
}
return false;
}
- /**
- * Declares a `_this` variable for derived classes and for when arrow functions capture `this`.
- *
- * @returns The new statement offset into the `statements` array.
- */
- function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) {
- // If this isn't a derived class, just capture 'this' for arrow functions if necessary.
- if (!isDerivedClass) {
- if (ctor) {
- addCaptureThisForNodeIfNeeded(statements, ctor);
- }
- return 0 /* NoReplacement */;
- }
- // We must be here because the user didn't write a constructor
- // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
- // If that's the case we can just immediately return the result of a 'super()' call.
- if (!ctor) {
- statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
- return 2 /* ReplaceWithReturn */;
- }
- // The constructor exists, but it and the 'super()' call it contains were generated
- // for something like property initializers.
- // Create a captured '_this' variable and assume it will subsequently be used.
- if (hasSynthesizedSuper) {
- captureThisForNode(statements, ctor, createDefaultSuperCallOrThis());
- enableSubstitutionsForCapturedThis();
- return 1 /* ReplaceSuperCapture */;
- }
- // Most of the time, a 'super' call will be the first real statement in a constructor body.
- // In these cases, we'd like to transform these into a *single* statement instead of a declaration
- // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer,
- // we'd get:
- //
- // var _this;
- // _this = _super.call(...) || this;
- //
- // instead of
- //
- // var _this = _super.call(...) || this;
- //
- // Additionally, if the 'super()' call is the last statement, we should just avoid capturing
- // entirely and immediately return the result like so:
- //
- // return _super.call(...) || this;
- //
- var firstStatement;
- var superCallExpression;
- var ctorStatements = ctor.body.statements;
- if (statementOffset < ctorStatements.length) {
- firstStatement = ctorStatements[statementOffset];
- if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) {
- superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
- }
- }
- // Return the result if we have an immediate super() call on the last statement,
- // but only if the constructor itself doesn't use 'this' elsewhere.
- if (superCallExpression
- && statementOffset === ctorStatements.length - 1
- && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) {
- var returnStatement = ts.createReturn(superCallExpression);
- if (superCallExpression.kind !== 204 /* BinaryExpression */
- || superCallExpression.left.kind !== 191 /* 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.
- ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */)));
- statements.push(returnStatement);
- return 2 /* ReplaceWithReturn */;
- }
- // Perform the capture.
- 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 */;
- }
- return 0 /* NoReplacement */;
- }
function createActualThis() {
return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
}
@@ -71922,14 +72910,9 @@
return node;
}
}
- /**
- * Gets a value indicating whether we need to add default value assignments for a
- * function-like node.
- *
- * @param node A function-like node.
- */
- function shouldAddDefaultValueAssignments(node) {
- return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0;
+ function hasDefaultValueOrBindingPattern(node) {
+ return node.initializer !== undefined
+ || ts.isBindingPattern(node.name);
}
/**
* Adds statements to the body of a function-like node if it contains parameters with
@@ -71939,9 +72922,10 @@
* @param node A function-like node.
*/
function addDefaultValueAssignmentsIfNeeded(statements, node) {
- if (!shouldAddDefaultValueAssignments(node)) {
- return;
+ if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
+ return false;
}
+ var added = false;
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
@@ -71951,12 +72935,14 @@
continue;
}
if (ts.isBindingPattern(name)) {
- addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer);
+ added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
}
else if (initializer) {
- addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
+ insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
+ added = true;
}
}
+ return added;
}
/**
* Adds statements to the body of a function-like node for parameters with binding patterns
@@ -71966,18 +72952,20 @@
* @param name The name of the parameter.
* @param initializer The initializer for the parameter.
*/
- function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
- var temp = ts.getGeneratedNameForNode(parameter);
+ function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
// In cases where a binding pattern is simply '[]' or '{}',
// we usually don't want to emit a var declaration; however, in the presence
// of an initializer, we must emit that expression to preserve side effects.
if (name.elements.length > 0) {
- statements.push(ts.setEmitFlags(ts.createVariableStatement(
- /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */));
+ ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(
+ /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
+ return true;
}
else if (initializer) {
- statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
+ ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
+ return true;
}
+ return false;
}
/**
* Adds statements to the body of a function-like node for parameters with initializers.
@@ -71987,7 +72975,7 @@
* @param name The name of the parameter.
* @param initializer The initializer for the parameter.
*/
- function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
+ function insertDefaultValueAssignmentForInitializer(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.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 */))
@@ -71995,7 +72983,7 @@
ts.startOnNewLine(statement);
ts.setTextRange(statement, parameter);
ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
- statements.push(statement);
+ ts.insertStatementAfterCustomPrologue(statements, statement);
}
/**
* Gets a value indicating whether we need to add statements to handle a rest parameter.
@@ -72018,9 +73006,10 @@
* synthesized call to `super`
*/
function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
+ var prologueStatements = [];
var parameter = ts.lastOrUndefined(node.parameters);
if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
- return;
+ return false;
}
// `declarationName` is the name of the local declaration for the parameter.
var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined);
@@ -72030,7 +73019,7 @@
var restIndex = node.parameters.length - 1;
var temp = ts.createLoopVariable();
// var param = [];
- statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
+ prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList([
ts.createVariableDeclaration(declarationName,
/*type*/ undefined, ts.createArrayLiteral([]))
@@ -72049,25 +73038,30 @@
]));
ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
ts.startOnNewLine(forStatement);
- statements.push(forStatement);
+ prologueStatements.push(forStatement);
if (parameter.name.kind !== 72 /* Identifier */) {
// do the actual destructuring of the rest parameter if necessary
- statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
+ prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
}
+ ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
+ return true;
}
/**
* Adds a statement to capture the `this` of a function declaration if it is needed.
+ * NOTE: This must be executed *after* the subtree has been visited.
*
* @param statements The statements for the new function body.
* @param node A node.
*/
- function addCaptureThisForNodeIfNeeded(statements, node) {
- if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) {
- captureThisForNode(statements, node, ts.createThis());
+ function insertCaptureThisForNodeIfNeeded(statements, node) {
+ if (hierarchyFacts & 16384 /* CapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) {
+ insertCaptureThisForNode(statements, node, ts.createThis());
+ return true;
}
+ return false;
}
- function captureThisForNode(statements, node, initializer) {
+ function insertCaptureThisForNode(statements, node, initializer) {
enableSubstitutionsForCapturedThis();
var captureThisStatement = ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList([
@@ -72076,10 +73070,10 @@
]));
ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
ts.setSourceMapRange(captureThisStatement, node);
- statements.push(captureThisStatement);
+ ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
}
- function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
- if (hierarchyFacts & 16384 /* NewTarget */) {
+ function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
+ if (hierarchyFacts & 8192 /* NewTarget */) {
var newTarget = void 0;
switch (node.kind) {
case 197 /* ArrowFunction */:
@@ -72110,10 +73104,11 @@
ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"),
/*type*/ undefined, newTarget)
]));
+ ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
if (copyOnWrite) {
- return [captureNewTargetStatement].concat(statements);
+ statements = statements.slice();
}
- statements.unshift(captureNewTargetStatement);
+ ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
}
return statements;
}
@@ -72165,7 +73160,6 @@
* @param member The MethodDeclaration node.
*/
function transformClassMethodDeclarationToStatement(receiver, member, container) {
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
var commentRange = ts.getCommentRange(member);
var sourceMapRange = ts.getSourceMapRange(member);
var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name);
@@ -72180,7 +73174,6 @@
// No source map should be emitted for this statement to align with the
// old emitter.
ts.setEmitFlags(statement, 48 /* NoSourceMap */);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return statement;
}
/**
@@ -72206,7 +73199,6 @@
*/
function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
// To align with source maps in the old emitter, the receiver and property name
// arguments are both mapped contiguously to the accessor name.
var target = ts.getMutableClone(receiver);
@@ -72242,7 +73234,6 @@
if (startsOnNewLine) {
ts.startOnNewLine(call);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return call;
}
/**
@@ -72251,12 +73242,12 @@
* @param node An ArrowFunction node.
*/
function visitArrowFunction(node) {
- if (node.transformFlags & 8192 /* ContainsLexicalThis */) {
- enableSubstitutionsForCapturedThis();
+ if (node.transformFlags & 2048 /* ContainsLexicalThis */) {
+ hierarchyFacts |= 16384 /* CapturedLexicalThis */;
}
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
+ var ancestorFacts = enterSubtree(8064 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
var func = ts.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
@@ -72266,7 +73257,11 @@
ts.setTextRange(func, node);
ts.setOriginalNode(func, node);
ts.setEmitFlags(func, 8 /* CapturesThis */);
- exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
+ if (hierarchyFacts & 16384 /* CapturedLexicalThis */) {
+ enableSubstitutionsForCapturedThis();
+ }
+ // If an arrow function contains
+ exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return func;
}
@@ -72277,18 +73272,16 @@
*/
function visitFunctionExpression(node) {
var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
- ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
- : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ ? enterSubtree(8086 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
+ : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & 64 /* ES2015 */
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
- var name = hierarchyFacts & 16384 /* NewTarget */
+ var body = transformFunctionBody(node);
+ var name = hierarchyFacts & 8192 /* NewTarget */
? ts.getLocalName(node)
: node.name;
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.updateFunctionExpression(node,
/*modifiers*/ undefined, node.asteriskToken, name,
@@ -72303,15 +73296,13 @@
function visitFunctionDeclaration(node) {
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & 64 /* ES2015 */
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
- var name = hierarchyFacts & 16384 /* NewTarget */
+ var body = transformFunctionBody(node);
+ var name = hierarchyFacts & 8192 /* NewTarget */
? ts.getLocalName(node)
: node.name;
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.updateFunctionDeclaration(node,
/*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name,
@@ -72329,14 +73320,14 @@
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
- ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
- : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ ? enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
+ : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var parameters = ts.visitParameterList(node.parameters, visitor, context);
var body = transformFunctionBody(node);
- if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) {
+ if (hierarchyFacts & 8192 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) {
name = ts.getGeneratedNameForNode(node);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
/*modifiers*/ undefined, node.asteriskToken, name,
@@ -72354,7 +73345,7 @@
var singleLine = false; // indicates whether the block *may* be emitted as a single line
var statementsLocation;
var closeBraceLocation;
- var leadingStatements = [];
+ var prologue = [];
var statements = [];
var body = node.body;
var statementOffset;
@@ -72362,14 +73353,13 @@
if (ts.isBlock(body)) {
// ensureUseStrict is false because no new prologue-directive should be added.
// addStandardPrologue will put already-existing directives at the beginning of the target statement-array
- statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false);
+ statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false);
}
- addCaptureThisForNodeIfNeeded(leadingStatements, node);
- addDefaultValueAssignmentsIfNeeded(leadingStatements, node);
- addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false);
+ multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
+ multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
if (ts.isBlock(body)) {
// addCustomPrologue puts already-existing directives at the beginning of the target statement-array
- statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor);
+ statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
statementsLocation = body.statements;
ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
// If the original body was a multi-line block, this must be a multi-line block.
@@ -72403,14 +73393,19 @@
// source map location for the close brace.
closeBraceLocation = body;
}
- var lexicalEnvironment = context.endLexicalEnvironment();
- ts.addStatementsAfterPrologue(statements, lexicalEnvironment);
- prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false);
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
+ insertCaptureThisForNodeIfNeeded(prologue, node);
// If we added any final generated statements, this must be a multi-line block
- if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) {
+ if (ts.some(prologue)) {
multiLine = true;
}
- var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine);
+ statements.unshift.apply(statements, prologue);
+ if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
+ // no changes were made, preserve the tree
+ return body;
+ }
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
ts.setTextRange(block, node.body);
if (!multiLine && singleLine) {
ts.setEmitFlags(block, 1 /* SingleLine */);
@@ -72421,11 +73416,6 @@
ts.setOriginalNode(block, node.body);
return block;
}
- function visitFunctionBodyDownLevel(node) {
- var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context);
- return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)),
- /*location*/ updated.statements));
- }
function visitBlock(node, isFunctionBody) {
if (isFunctionBody) {
// A function body is not a block scope.
@@ -72530,7 +73520,7 @@
* @param node A VariableDeclarationList node.
*/
function visitVariableDeclarationList(node) {
- if (node.transformFlags & 64 /* ES2015 */) {
+ if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 65536 /* ContainsBindingPattern */) {
if (node.flags & 3 /* BlockScoped */) {
enableSubstitutionsForBlockScopedBindings();
}
@@ -72543,7 +73533,7 @@
ts.setCommentRange(declarationList, node);
// If the first or last declaration is a binding pattern, we need to modify
// the source map range for the declaration list.
- if (node.transformFlags & 2097152 /* ContainsBindingPattern */
+ if (node.transformFlags & 65536 /* ContainsBindingPattern */
&& (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
}
@@ -72865,7 +73855,7 @@
var numInitialPropertiesWithoutYield = numProperties;
for (var i = 0; i < numProperties; i++) {
var property = properties[i];
- if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
+ if ((property.transformFlags & 131072 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
&& i < numInitialPropertiesWithoutYield) {
numInitialPropertiesWithoutYield = i;
}
@@ -73141,7 +74131,7 @@
*/
function createFunctionForInitializerOfForStatement(node, currentState) {
var functionName = ts.createUniqueName("_loop_init");
- var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ var containsYield = (node.initializer.transformFlags & 131072 /* ContainsYield */) !== 0;
var emitFlags = 0 /* None */;
if (currentState.containsLexicalThis)
emitFlags |= 8 /* CapturesThis */;
@@ -73246,11 +74236,11 @@
statements.push(statement);
}
copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
- ts.addStatementsAfterPrologue(statements, lexicalEnvironment);
+ ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
var loopBody = ts.createBlock(statements, /*multiLine*/ true);
if (ts.isBlock(statement))
ts.setOriginalNode(loopBody, statement);
- var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ var containsYield = (node.statement.transformFlags & 131072 /* ContainsYield */) !== 0;
var emitFlags = 0;
if (currentState.containsLexicalThis)
emitFlags |= 8 /* CapturesThis */;
@@ -73482,13 +74472,11 @@
* @param receiver The receiver for the assignment.
*/
function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
ts.setTextRange(expression, method);
if (startsOnNewLine) {
ts.startOnNewLine(expression);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return expression;
}
function visitCatchClause(node) {
@@ -73540,19 +74528,17 @@
ts.Debug.assert(!ts.isComputedPropertyName(node.name));
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var updated;
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */)
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
+ var body = transformFunctionBody(node);
if (node.kind === 158 /* GetAccessor */) {
updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
}
else {
updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return updated;
}
@@ -73566,10 +74552,7 @@
/*location*/ node);
}
function visitComputedPropertyName(node) {
- var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */);
- var updated = ts.visitEachChild(node, visitor, context);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */);
- return updated;
+ return ts.visitEachChild(node, visitor, context);
}
/**
* Visits a YieldExpression node.
@@ -73586,7 +74569,7 @@
* @param node An ArrayLiteralExpression node.
*/
function visitArrayLiteralExpression(node) {
- if (node.transformFlags & 64 /* ES2015 */) {
+ if (ts.some(node.elements, ts.isSpreadElement)) {
// We are here because we contain a SpreadElementExpression.
return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
}
@@ -73601,7 +74584,10 @@
if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
return visitTypeScriptClassWrapper(node);
}
- if (node.transformFlags & 64 /* ES2015 */) {
+ var expression = ts.skipOuterExpressions(node.expression);
+ if (expression.kind === 98 /* SuperKeyword */ ||
+ ts.isSuperProperty(expression) ||
+ ts.some(node.arguments, ts.isSpreadElement)) {
return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
}
return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression),
@@ -73722,7 +74708,7 @@
function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
// We are here either because SuperKeyword was used somewhere in the expression, or
// because we contain a SpreadElementExpression.
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */ ||
+ if (node.transformFlags & 4096 /* ContainsRestOrSpread */ ||
node.expression.kind === 98 /* SuperKeyword */ ||
ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
@@ -73730,7 +74716,7 @@
ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
}
var resultingCall = void 0;
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */) {
+ if (node.transformFlags & 4096 /* ContainsRestOrSpread */) {
// [source]
// f(...a, b)
// x.m(...a, b)
@@ -73744,7 +74730,7 @@
// _super.apply(this, a.concat([b]))
// _super.m.apply(this, a.concat([b]))
// _super.prototype.m.apply(this, a.concat([b]))
- resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
+ resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
}
else {
// [source]
@@ -73756,13 +74742,11 @@
// _super.call(this, a)
// _super.m.call(this, a)
// _super.prototype.m.call(this, a)
- resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
+ resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
/*location*/ node);
}
if (node.expression.kind === 98 /* SuperKeyword */) {
- var actualThis = ts.createThis();
- ts.setEmitFlags(actualThis, 4 /* NoSubstitution */);
- var initializer = ts.createLogicalOr(resultingCall, actualThis);
+ var initializer = ts.createLogicalOr(resultingCall, createActualThis());
resultingCall = assignToCapturedThis
? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
: initializer;
@@ -73777,7 +74761,7 @@
* @param node A NewExpression node.
*/
function visitNewExpression(node) {
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */) {
+ if (ts.some(node.arguments, ts.isSpreadElement)) {
// We are here because we contain a SpreadElementExpression.
// [source]
// new C(...a)
@@ -74040,12 +75024,7 @@
}
function visitMetaProperty(node) {
if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") {
- if (hierarchyFacts & 8192 /* ComputedPropertyName */) {
- hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */;
- }
- else {
- hierarchyFacts |= 16384 /* NewTarget */;
- }
+ hierarchyFacts |= 8192 /* NewTarget */;
return ts.createFileLevelUniqueName("_newTarget");
}
return node;
@@ -74060,7 +75039,7 @@
function onEmitNode(hint, node, emitCallback) {
if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
// If we are tracking a captured `this`, keep track of the enclosing function.
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
: 65 /* FunctionIncludes */);
previousOnEmitNode(hint, node, emitCallback);
@@ -74240,7 +75219,7 @@
}
ts.transformES2015 = transformES2015;
function createExtendsHelper(context, name) {
- context.requestEmitHelper(extendsHelper);
+ context.requestEmitHelper(ts.extendsHelper);
return ts.createCall(ts.getHelperName("__extends"),
/*typeArguments*/ undefined, [
name,
@@ -74248,20 +75227,20 @@
]);
}
function createTemplateObjectHelper(context, cooked, raw) {
- context.requestEmitHelper(templateObjectHelper);
+ context.requestEmitHelper(ts.templateObjectHelper);
return ts.createCall(ts.getHelperName("__makeTemplateObject"),
/*typeArguments*/ undefined, [
cooked,
raw
]);
}
- var extendsHelper = {
+ ts.extendsHelper = {
name: "typescript:extends",
scoped: false,
priority: 0,
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 = {
+ ts.templateObjectHelper = {
name: "typescript:makeTemplateObject",
scoped: false,
priority: 0,
@@ -74608,7 +75587,7 @@
var withBlockStack; // A stack containing `with` blocks.
return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
- if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
+ if (node.isDeclarationFile || (node.transformFlags & 256 /* ContainsGenerator */) === 0) {
return node;
}
var visited = ts.visitEachChild(node, visitor, context);
@@ -74628,10 +75607,10 @@
else if (inGeneratorFunctionBody) {
return visitJavaScriptInGeneratorFunctionBody(node);
}
- else if (transformFlags & 256 /* Generator */) {
+ else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
return visitGenerator(node);
}
- else if (transformFlags & 512 /* ContainsGenerator */) {
+ else if (transformFlags & 256 /* ContainsGenerator */) {
return ts.visitEachChild(node, visitor, context);
}
else {
@@ -74684,10 +75663,10 @@
case 230 /* ReturnStatement */:
return visitReturnStatement(node);
default:
- if (node.transformFlags & 4194304 /* ContainsYield */) {
+ if (node.transformFlags & 131072 /* ContainsYield */) {
return visitJavaScriptContainingYield(node);
}
- else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) {
+ else if (node.transformFlags & (256 /* ContainsGenerator */ | 262144 /* ContainsHoistedDeclarationOrCompletion */)) {
return ts.visitEachChild(node, visitor, context);
}
else {
@@ -74863,7 +75842,7 @@
var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
transformAndEmitStatements(body.statements, statementOffset);
var buildResult = build();
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
statements.push(ts.createReturn(buildResult));
// Restore previous generator state
inGeneratorFunctionBody = savedInGeneratorFunctionBody;
@@ -74890,7 +75869,7 @@
* @param node The node to visit.
*/
function visitVariableStatement(node) {
- if (node.transformFlags & 4194304 /* ContainsYield */) {
+ if (node.transformFlags & 131072 /* ContainsYield */) {
transformAndEmitVariableDeclarationList(node.declarationList);
return undefined;
}
@@ -75948,7 +76927,7 @@
}
}
function containsYield(node) {
- return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ return !!node && (node.transformFlags & 131072 /* ContainsYield */) !== 0;
}
function countInitialNodesWithoutYield(nodes) {
var numNodes = nodes.length;
@@ -76955,7 +77934,7 @@
}
ts.transformGenerators = transformGenerators;
function createGeneratorHelper(context, body) {
- context.requestEmitHelper(generatorHelper);
+ context.requestEmitHelper(ts.generatorHelper);
return ts.createCall(ts.getHelperName("__generator"),
/*typeArguments*/ undefined, [ts.createThis(), body]);
}
@@ -77018,7 +77997,7 @@
// entering a finally block.
//
// For examples of how these are used, see the comments in ./transformers/generators.ts
- var generatorHelper = {
+ ts.generatorHelper = {
name: "typescript:generator",
scoped: false,
priority: 6,
@@ -77051,7 +78030,7 @@
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* 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.
@@ -77067,7 +78046,7 @@
function transformSourceFile(node) {
if (node.isDeclarationFile ||
!(ts.isEffectiveExternalModule(node, compilerOptions) ||
- node.transformFlags & 16777216 /* ContainsDynamicImport */ ||
+ node.transformFlags & 524288 /* ContainsDynamicImport */ ||
(ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
return node;
}
@@ -77104,7 +78083,7 @@
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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(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
@@ -77330,7 +78309,7 @@
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
// End the lexical environment for the module body
// and merge any new lexical declarations.
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var body = ts.createBlock(statements, /*multiLine*/ true);
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
// If we have any `export * from ...` declarations
@@ -77393,9 +78372,9 @@
return visitFunctionDeclaration(node);
case 240 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
@@ -77404,13 +78383,13 @@
function moduleExpressionElementVisitor(node) {
// This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
// as export/import statements are only transformed at the top level of a file.
- if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) {
+ if (!(node.transformFlags & 524288 /* ContainsDynamicImport */) && !(node.transformFlags & 512 /* ContainsDestructuringAssignment */)) {
return node;
}
if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
- else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) {
+ else if (ts.isDestructuringAssignment(node)) {
return visitDestructuringAssignment(node);
}
else {
@@ -77471,7 +78450,7 @@
}
function visitImportCallExpression(node) {
var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
- var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */);
+ var containsLexicalThis = !!(node.transformFlags & 2048 /* ContainsLexicalThis */);
switch (compilerOptions.module) {
case ts.ModuleKind.AMD:
return createImportCallExpressionAMD(argument, containsLexicalThis);
@@ -77553,7 +78532,7 @@
}
var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]);
}
return promise;
@@ -77567,7 +78546,7 @@
var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
}
var func;
@@ -77601,11 +78580,11 @@
return innerExpr;
}
if (ts.getImportNeedsImportStarHelper(node)) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
}
if (ts.getImportNeedsImportDefaultHelper(node)) {
- context.requestEmitHelper(importDefaultHelper);
+ context.requestEmitHelper(ts.importDefaultHelper);
return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
}
return innerExpr;
@@ -78174,7 +79153,7 @@
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
currentSourceFile = node;
currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
noSubstitution = [];
@@ -78262,7 +79241,7 @@
}
if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)),
/*location*/ node);
}
@@ -78388,13 +79367,13 @@
text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
};
// emit helper for `import * as Name from "foo"`
- var importStarHelper = {
+ ts.importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
// emit helper for `import Name from "foo"`
- var importDefaultHelper = {
+ ts.importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
@@ -78417,7 +79396,7 @@
context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols.
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* 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.
@@ -78436,7 +79415,7 @@
* @param node The SourceFile node.
*/
function transformSourceFile(node) {
- if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) {
+ if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 524288 /* ContainsDynamicImport */)) {
return node;
}
var id = ts.getOriginalNodeId(node);
@@ -78602,7 +79581,7 @@
// 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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
var moduleObject = ts.createObjectLiteral([
ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
@@ -78987,7 +79966,7 @@
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 === 279 /* SourceFile */
+ && (enclosingBlockScopedContainer.kind === 284 /* SourceFile */
|| (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
}
/**
@@ -79330,9 +80309,9 @@
return visitCatchClause(node);
case 218 /* Block */:
return visitBlock(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -79514,14 +80493,13 @@
* @param node The node to visit.
*/
function destructuringAndImportCallVisitor(node) {
- if (node.transformFlags & 1024 /* DestructuringAssignment */
- && node.kind === 204 /* BinaryExpression */) {
+ if (ts.isDestructuringAssignment(node)) {
return visitDestructuringAssignment(node);
}
else if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
- else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) {
+ else if ((node.transformFlags & 512 /* ContainsDestructuringAssignment */) || (node.transformFlags & 524288 /* ContainsDynamicImport */)) {
return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
}
else {
@@ -79580,7 +80558,7 @@
}
else if (ts.isIdentifier(node)) {
var container = resolver.getReferencedExportContainer(node);
- return container !== undefined && container.kind === 279 /* SourceFile */;
+ return container !== undefined && container.kind === 284 /* SourceFile */;
}
else {
return false;
@@ -79613,7 +80591,7 @@
* @param emitCallback A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
var id = ts.getOriginalNodeId(node);
currentSourceFile = node;
moduleInfo = moduleInfoMap[id];
@@ -79822,7 +80800,7 @@
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
}
exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
@@ -79861,7 +80839,7 @@
var previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- context.enableEmitNotification(279 /* SourceFile */);
+ context.enableEmitNotification(284 /* SourceFile */);
context.enableSubstitution(72 /* Identifier */);
var currentSourceFile;
return ts.chainBundle(transformSourceFile);
@@ -79971,7 +80949,8 @@
ts.isImportEqualsDeclaration(node) ||
ts.isTypeAliasDeclaration(node) ||
ts.isConstructorDeclaration(node) ||
- ts.isIndexSignatureDeclaration(node);
+ ts.isIndexSignatureDeclaration(node) ||
+ ts.isPropertyAccessExpression(node);
}
ts.canProduceDiagnostics = canProduceDiagnostics;
function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
@@ -80045,7 +81024,7 @@
}
ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
function createGetSymbolAccessibilityDiagnosticForNode(node) {
- if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
+ if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
return getVariableDeclarationTypeVisibilityError;
}
else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
@@ -80085,7 +81064,7 @@
}
// This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
// The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
- else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ ||
+ else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 189 /* PropertyAccessExpression */ || node.kind === 153 /* PropertySignature */ ||
(node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
// TODO(jfreeman): Deal with computed properties in error reporting.
if (ts.hasModifier(node, 32 /* Static */)) {
@@ -80290,6 +81269,9 @@
case 241 /* InterfaceDeclaration */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
break;
+ case 181 /* MappedType */:
+ diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
+ break;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
@@ -80373,6 +81355,31 @@
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
+ function hasInternalAnnotation(range, currentSourceFile) {
+ var comment = currentSourceFile.text.substring(range.pos, range.end);
+ return ts.stringContains(comment, "@internal");
+ }
+ function isInternalDeclaration(node, currentSourceFile) {
+ var parseTreeNode = ts.getParseTreeNode(node);
+ if (parseTreeNode && parseTreeNode.kind === 151 /* Parameter */) {
+ var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
+ var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
+ var text = currentSourceFile.text;
+ var commentRanges = previousSibling
+ ? ts.concatenate(
+ // to handle
+ // ... parameters, /* @internal */
+ // public param: string
+ ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
+ : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
+ return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
+ }
+ var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
+ return !!ts.forEach(leadingCommentRanges, function (range) {
+ return hasInternalAnnotation(range, currentSourceFile);
+ });
+ }
+ ts.isInternalDeclaration = isInternalDeclaration;
var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
2048 /* WriteClassExpressionAsTypeLiteral */ |
4096 /* UseTypeOfFunction */ |
@@ -80501,10 +81508,10 @@
}
}
function transformRoot(node) {
- if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
+ if (node.kind === 284 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
}
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
isBundledEmit = true;
refs = ts.createMap();
libs = ts.createMap();
@@ -80534,9 +81541,15 @@
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 === 282 /* InputFiles */) {
- return ts.createUnparsedSourceFile(prepend, "dts");
+ if (prepend.kind === 287 /* InputFiles */) {
+ var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
+ hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
+ collectReferences(sourceFile, refs);
+ recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
+ collectLibs(sourceFile, libs);
+ return sourceFile;
}
+ return prepend;
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -80628,7 +81641,7 @@
}
}
function collectReferences(sourceFile, ret) {
- if (noResolve || ts.isSourceFileJS(sourceFile))
+ if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
return ret;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
@@ -81175,7 +82188,9 @@
if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
return undefined;
}
+ getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker);
+ getSymbolAccessibilityDiagnostic = oldDiag;
var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
});
@@ -81218,7 +82233,7 @@
if (ctor) {
var oldDiag_1 = getSymbolAccessibilityDiagnostic;
parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
- if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */))
+ if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
return;
getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
if (param.name.kind === 72 /* Identifier */) {
@@ -81354,18 +82369,8 @@
}
errorNameNode = undefined;
}
- function hasInternalAnnotation(range) {
- var comment = currentSourceFile.text.substring(range.pos, range.end);
- return ts.stringContains(comment, "@internal");
- }
function shouldStripInternal(node) {
- if (stripInternal && node) {
- var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile);
- if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
- return true;
- }
- }
- return false;
+ return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
}
function isScopeMarker(node) {
return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
@@ -81387,7 +82392,7 @@
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 === 279 /* SourceFile */;
+ var parentIsFile = node.parent.kind === 284 /* SourceFile */;
if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */);
additions = 0 /* None */;
@@ -81556,9 +82561,15 @@
if (jsx === 2 /* React */) {
transformers.push(ts.transformJsx);
}
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
transformers.push(ts.transformESNext);
}
+ if (languageVersion < 6 /* ES2019 */) {
+ transformers.push(ts.transformES2019);
+ }
+ if (languageVersion < 5 /* ES2018 */) {
+ transformers.push(ts.transformES2018);
+ }
if (languageVersion < 4 /* ES2017 */) {
transformers.push(ts.transformES2017);
}
@@ -81598,7 +82609,7 @@
* @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(312 /* Count */);
+ var enabledSyntaxKindFeatures = new Array(317 /* Count */);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -81858,10 +82869,14 @@
})(ts || (ts = {}));
var ts;
(function (ts) {
- var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
var syntheticParent = { pos: -1, end: -1 };
/*@internal*/
+ function isBuildInfoFile(file) {
+ return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
+ }
+ ts.isBuildInfoFile = isBuildInfoFile;
+ /*@internal*/
/**
* Iterates over the source files that are expected to have an emit output.
*
@@ -81871,13 +82886,14 @@
* 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, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
+ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles, onlyBuildInfo, includeBuildInfo) {
if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; }
var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
+ var prepends = host.getPrependNodes();
+ if (sourceFiles.length || prepends.length) {
+ var bundle = ts.createBundle(sourceFiles, prepends);
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -81885,6 +82901,7 @@
}
}
else {
+ if (!onlyBuildInfo) {
for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
var sourceFile = sourceFiles_1[_a];
var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
@@ -81893,23 +82910,52 @@
}
}
}
+ if (includeBuildInfo) {
+ var buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
+ if (buildInfoPath)
+ return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
+ }
+ }
}
ts.forEachEmittedFile = forEachEmittedFile;
/*@internal*/
+ function getOutputPathForBuildInfo(options) {
+ var configFile = options.configFilePath;
+ if (!configFile || !ts.isIncrementalCompilation(options))
+ return undefined;
+ if (options.tsBuildInfoFile)
+ return options.tsBuildInfoFile;
+ var outPath = options.outFile || options.out;
+ var buildInfoExtensionLess;
+ if (outPath) {
+ buildInfoExtensionLess = ts.removeFileExtension(outPath);
+ }
+ else {
+ var configFileExtensionLess = ts.removeFileExtension(configFile);
+ buildInfoExtensionLess = options.outDir ?
+ options.rootDir ?
+ ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
+ ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
+ configFileExtensionLess;
+ }
+ return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
+ }
+ ts.getOutputPathForBuildInfo = getOutputPathForBuildInfo;
+ /*@internal*/
function getOutputPathsForBundle(options, forceDtsPaths) {
var outPath = options.outFile || options.out;
var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
var declarationMapPath = declarationFilePath && 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 };
+ var buildInfoPath = getOutputPathForBuildInfo(options);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
}
ts.getOutputPathsForBundle = getOutputPathsForBundle;
/*@internal*/
function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
var options = host.getCompilerOptions();
- if (sourceFile.kind === 280 /* Bundle */) {
+ if (sourceFile.kind === 285 /* Bundle */) {
return getOutputPathsForBundle(options, forceDtsPaths);
}
else {
@@ -81923,19 +82969,13 @@
var isJs = ts.isSourceFileJS(sourceFile);
var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
}
}
ts.getOutputPathsFor = getOutputPathsFor;
function getSourceMapFilePath(jsFilePath, options) {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
- function createDefaultBundleInfo() {
- return {
- originalOffset: -1,
- totalLength: -1
- };
- }
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
@@ -81958,9 +82998,91 @@
return ".js" /* Js */;
}
ts.getOutputExtension = getOutputExtension;
+ function rootDirOfOptions(configFile) {
+ return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.assertDefined(configFile.options.configFilePath));
+ }
+ function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
+ return outputDir ?
+ ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
+ inputFileName;
+ }
+ /* @internal */
+ function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
+ ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(inputFileName));
+ return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
+ }
+ ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
+ function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
+ var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
+ var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
+ ".json" /* Json */ :
+ ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
+ ".jsx" /* Jsx */ :
+ ".js" /* Js */);
+ return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.assertDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
+ outputFileName :
+ undefined;
+ }
+ /*@internal*/
+ function getAllProjectOutputs(configFile, ignoreCase) {
+ var outputs;
+ var addOutput = function (path) { return path && (outputs || (outputs = [])).push(path); };
+ if (configFile.options.outFile || configFile.options.out) {
+ var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ addOutput(jsFilePath);
+ addOutput(sourceMapFilePath);
+ addOutput(declarationFilePath);
+ addOutput(declarationMapPath);
+ addOutput(buildInfoPath);
+ }
+ else {
+ for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
+ var inputFileName = _c[_b];
+ if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
+ continue;
+ var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ addOutput(js);
+ if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
+ continue;
+ if (configFile.options.sourceMap) {
+ addOutput(js + ".map");
+ }
+ if (ts.getEmitDeclarations(configFile.options) && ts.hasTSFileExtension(inputFileName)) {
+ var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
+ addOutput(dts);
+ if (configFile.options.declarationMap) {
+ addOutput(dts + ".map");
+ }
+ }
+ }
+ addOutput(getOutputPathForBuildInfo(configFile.options));
+ }
+ return outputs || ts.emptyArray;
+ }
+ ts.getAllProjectOutputs = getAllProjectOutputs;
+ /*@internal*/
+ function getFirstProjectOutput(configFile, ignoreCase) {
+ if (configFile.options.outFile || configFile.options.out) {
+ var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
+ return ts.Debug.assertDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
+ }
+ for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
+ var inputFileName = _b[_a];
+ if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
+ continue;
+ var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ if (jsFilePath)
+ return jsFilePath;
+ }
+ var buildInfoPath = getOutputPathForBuildInfo(configFile.options);
+ if (buildInfoPath)
+ return buildInfoPath;
+ return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
+ }
+ ts.getFirstProjectOutput = getFirstProjectOutput;
/*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers, onlyBuildInfo) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -81968,12 +83090,12 @@
var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
var writer = ts.createTextWriter(newLine);
var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit;
- var bundleInfo = createDefaultBundleInfo();
+ var bundleBuildInfo;
var emitSkipped = false;
var exportedModulesFromDeclarationEmit;
// Emit each output file
enter();
- forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles);
+ forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile);
exit();
return {
emitSkipped: emitSkipped,
@@ -81983,9 +83105,16 @@
exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
+ bundleBuildInfo = {
+ commonSourceDirectory: host.getCommonSourceDirectory(),
+ sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return file.fileName; })
+ };
+ }
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
+ emitBuildInfo(bundleBuildInfo, buildInfoPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
if (jsFilePath) {
@@ -81994,8 +83123,8 @@
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
- if (bundleInfoPath) {
- emittedFilesList.push(bundleInfoPath);
+ if (buildInfoPath) {
+ emittedFilesList.push(buildInfoPath);
}
}
if (declarationFilePath) {
@@ -82006,8 +83135,21 @@
}
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
- if (emitOnlyDtsFiles || !jsFilePath) {
+ function emitBuildInfo(bundle, buildInfoPath) {
+ // Write build information if applicable
+ if (!buildInfoPath || targetSourceFile || emitSkipped)
+ return;
+ var program = host.getProgramBuildInfo();
+ if (!bundle && !program)
+ return;
+ if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
+ emitSkipped = true;
+ return;
+ }
+ ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: ts.version }), /*writeByteOrderMark*/ false);
+ }
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
+ if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
return;
}
// Make sure not to write js file and source map file if any of them cannot be written
@@ -82027,6 +83169,7 @@
inlineSourceMap: compilerOptions.inlineSourceMap,
inlineSources: compilerOptions.inlineSources,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ writeBundleFileInfo: !!bundleBuildInfo
};
// Create a printer to print the nodes
var printer = createPrinter(printerOptions, {
@@ -82037,12 +83180,14 @@
substituteNode: transform.substituteNode,
});
ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions);
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
// Clean up emit nodes on parse tree
transform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.js = printer.bundleFileInfo;
}
function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) {
- if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
+ if (!sourceFileOrBundle || !(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
return;
}
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
@@ -82071,6 +83216,8 @@
inlineSourceMap: compilerOptions.inlineSourceMap,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
onlyPrintJsDocStyle: true,
+ writeBundleFileInfo: !!bundleBuildInfo,
+ recordInternalSection: !!bundleBuildInfo
};
var declarationPrinter = createPrinter(printerOptions, {
// resolver hooks
@@ -82083,18 +83230,20 @@
emitSkipped = emitSkipped || declBlocked;
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, {
+ printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
sourceMap: compilerOptions.declarationMap,
sourceRoot: compilerOptions.sourceRoot,
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
- if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) {
+ if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 284 /* SourceFile */) {
var sourceFile = declarationTransform.transformed[0];
exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
}
}
declarationTransform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
}
function collectLinkedAliases(node) {
if (ts.isExportAssignment(node)) {
@@ -82109,16 +83258,16 @@
}
ts.forEachChild(node, collectLinkedAliases);
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) {
- var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined;
- var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined;
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
+ var bundle = sourceFileOrBundle.kind === 285 /* Bundle */ ? sourceFileOrBundle : undefined;
+ var sourceFile = sourceFileOrBundle.kind === 284 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
var sourceMapGenerator;
if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
}
if (bundle) {
- printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator);
+ printer.writeBundle(bundle, writer, sourceMapGenerator);
}
else {
printer.writeFile(sourceFile, writer, sourceMapGenerator);
@@ -82147,18 +83296,12 @@
}
// Write the output file
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
- // Write bundled offset information if applicable
- if (bundleInfoPath) {
- bundleInfo.totalLength = writer.getTextPos();
- ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false);
- }
// Reset state
writer.clear();
- bundleInfo = createDefaultBundleInfo();
}
function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
- && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
+ && (sourceFileOrBundle.kind !== 284 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
}
function getSourceRoot(mapOptions) {
// Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
@@ -82215,6 +83358,167 @@
}
}
ts.emitFiles = emitFiles;
+ /*@internal*/
+ function getBuildInfoText(buildInfo) {
+ return JSON.stringify(buildInfo, undefined, 2);
+ }
+ ts.getBuildInfoText = getBuildInfoText;
+ /*@internal*/
+ function getBuildInfo(buildInfoText) {
+ return JSON.parse(buildInfoText);
+ }
+ ts.getBuildInfo = getBuildInfo;
+ /*@internal*/
+ ts.notImplementedResolver = {
+ hasGlobalName: ts.notImplemented,
+ getReferencedExportContainer: ts.notImplemented,
+ getReferencedImportDeclaration: ts.notImplemented,
+ getReferencedDeclarationWithCollidingName: ts.notImplemented,
+ isDeclarationWithCollidingName: ts.notImplemented,
+ isValueAliasDeclaration: ts.notImplemented,
+ isReferencedAliasDeclaration: ts.notImplemented,
+ isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
+ getNodeCheckFlags: ts.notImplemented,
+ isDeclarationVisible: ts.notImplemented,
+ isLateBound: function (_node) { return false; },
+ collectLinkedAliases: ts.notImplemented,
+ isImplementationOfOverload: ts.notImplemented,
+ isRequiredInitializedParameter: ts.notImplemented,
+ isOptionalUninitializedParameterProperty: ts.notImplemented,
+ isExpandoFunctionDeclaration: ts.notImplemented,
+ getPropertiesOfContainerFunction: ts.notImplemented,
+ createTypeOfDeclaration: ts.notImplemented,
+ createReturnTypeOfSignatureDeclaration: ts.notImplemented,
+ createTypeOfExpression: ts.notImplemented,
+ createLiteralConstValue: ts.notImplemented,
+ isSymbolAccessible: ts.notImplemented,
+ isEntityNameVisible: ts.notImplemented,
+ // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
+ getConstantValue: ts.notImplemented,
+ getReferencedValueDeclaration: ts.notImplemented,
+ getTypeReferenceSerializationKind: ts.notImplemented,
+ isOptionalParameter: ts.notImplemented,
+ moduleExportsSomeValue: ts.notImplemented,
+ isArgumentsLocalBinding: ts.notImplemented,
+ getExternalModuleFileFromDeclaration: ts.notImplemented,
+ getTypeReferenceDirectivesForEntityName: ts.notImplemented,
+ getTypeReferenceDirectivesForSymbol: ts.notImplemented,
+ isLiteralConstDeclaration: ts.notImplemented,
+ getJsxFactoryEntity: ts.notImplemented,
+ getAllAccessorDeclarations: ts.notImplemented,
+ getSymbolOfExternalModuleSpecifier: ts.notImplemented,
+ isBindingCapturedByNode: ts.notImplemented,
+ };
+ function createSourceFilesFromBundleBuildInfo(bundle) {
+ var sourceFiles = bundle.sourceFiles.map(function (fileName) {
+ var sourceFile = ts.createNode(284 /* SourceFile */, 0, 0);
+ sourceFile.fileName = fileName;
+ sourceFile.text = "";
+ sourceFile.statements = ts.createNodeArray();
+ return sourceFile;
+ });
+ var jsBundle = ts.Debug.assertDefined(bundle.js);
+ ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
+ var sourceFile = sourceFiles[prologueInfo.file];
+ sourceFile.text = prologueInfo.text;
+ sourceFile.end = prologueInfo.text.length;
+ sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
+ var statement = ts.createNode(221 /* ExpressionStatement */, directive.pos, directive.end);
+ statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
+ statement.expression.text = directive.expression.text;
+ return statement;
+ }));
+ });
+ return sourceFiles;
+ }
+ /*@internal*/
+ function emitUsingBuildInfo(config, host, getCommandLine) {
+ var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
+ var buildInfoText = host.readFile(ts.Debug.assertDefined(buildInfoPath));
+ if (!buildInfoText)
+ return buildInfoPath;
+ var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath));
+ if (!jsFileText)
+ return jsFilePath;
+ var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
+ // error if no source map or for now if inline sourcemap
+ if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
+ return sourceMapFilePath || "inline sourcemap decoding";
+ // read declaration text
+ var declarationText = declarationFilePath && host.readFile(declarationFilePath);
+ if (declarationFilePath && !declarationText)
+ return declarationFilePath;
+ var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
+ // error if no source map or for now if inline sourcemap
+ if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
+ return declarationMapPath || "inline sourcemap decoding";
+ var buildInfo = getBuildInfo(buildInfoText);
+ if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
+ return buildInfoPath;
+ var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo,
+ /*onlyOwnText*/ true);
+ var outputFiles = [];
+ var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
+ var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle);
+ var emitHost = {
+ getPrependNodes: ts.memoize(function () { return prependNodes.concat([ownPrependInput]); }),
+ getCanonicalFileName: host.getCanonicalFileName,
+ getCommonSourceDirectory: function () { return buildInfo.bundle.commonSourceDirectory; },
+ getCompilerOptions: function () { return config.options; },
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ getNewLine: function () { return host.getNewLine(); },
+ getSourceFile: ts.returnUndefined,
+ getSourceFileByPath: ts.returnUndefined,
+ getSourceFiles: function () { return sourceFilesForJsEmit; },
+ getLibFileFromReference: ts.notImplemented,
+ isSourceFileFromExternalLibrary: ts.returnFalse,
+ getResolvedProjectReferenceToRedirect: ts.returnUndefined,
+ writeFile: function (name, text, writeByteOrderMark) {
+ switch (name) {
+ case jsFilePath:
+ if (jsFileText === text)
+ return;
+ break;
+ case sourceMapFilePath:
+ if (sourceMapText === text)
+ return;
+ break;
+ case buildInfoPath:
+ var newBuildInfo = getBuildInfo(text);
+ newBuildInfo.program = buildInfo.program;
+ // Update sourceFileInfo
+ var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
+ newBuildInfo.bundle.js.sources = js.sources;
+ if (dts) {
+ newBuildInfo.bundle.dts.sources = dts.sources;
+ }
+ newBuildInfo.bundle.sourceFiles = sourceFiles;
+ outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
+ return;
+ case declarationFilePath:
+ if (declarationText === text)
+ return;
+ break;
+ case declarationMapPath:
+ if (declarationMapText === text)
+ return;
+ break;
+ default:
+ ts.Debug.fail("Unexpected path: " + name);
+ }
+ outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
+ },
+ isEmitBlocked: ts.returnFalse,
+ readFile: function (f) { return host.readFile(f); },
+ fileExists: function (f) { return host.fileExists(f); },
+ directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }),
+ useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
+ getProgramBuildInfo: ts.returnUndefined
+ };
+ emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, /*emitOnlyDtsFiles*/ false, ts.getTransformers(config.options));
+ return outputFiles;
+ }
+ ts.emitUsingBuildInfo = emitUsingBuildInfo;
var PipelinePhase;
(function (PipelinePhase) {
PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
@@ -82243,6 +83547,10 @@
var ownWriter; // Reusable `EmitTextWriter` for basic printing.
var write = writeBase;
var isOwnFileEmit;
+ var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
+ var recordInternalSection = printerOptions.recordInternalSection;
+ var sourceFileTextPos = 0;
+ var sourceFileTextKind = "text" /* Text */;
// Source Maps
var sourceMapsDisabled = true;
var sourceMapGenerator;
@@ -82268,7 +83576,8 @@
writeNode: writeNode,
writeList: writeList,
writeFile: writeFile,
- writeBundle: writeBundle
+ writeBundle: writeBundle,
+ bundleFileInfo: bundleFileInfo
};
function printNode(hint, node, sourceFile) {
switch (hint) {
@@ -82283,9 +83592,9 @@
break;
}
switch (node.kind) {
- case 279 /* SourceFile */: return printFile(node);
- case 280 /* Bundle */: return printBundle(node);
- case 281 /* UnparsedSource */: return printUnparsedSource(node);
+ case 284 /* SourceFile */: return printFile(node);
+ case 285 /* Bundle */: return printBundle(node);
+ case 286 /* UnparsedSource */: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -82295,7 +83604,7 @@
return endPrint();
}
function printBundle(bundle) {
- writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined);
+ writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
return endPrint();
}
function printFile(sourceFile) {
@@ -82323,7 +83632,49 @@
reset();
writer = previousWriter;
}
- function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) {
+ function getTextPosWithWriteLine() {
+ return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
+ }
+ function updateOrPushBundleFileTextLike(pos, end, kind) {
+ var last = ts.lastOrUndefined(bundleFileInfo.sections);
+ if (last && last.kind === kind) {
+ last.end = end;
+ }
+ else {
+ bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
+ }
+ }
+ function recordBundleFileInternalSectionStart(node) {
+ if (recordInternalSection &&
+ bundleFileInfo &&
+ currentSourceFile &&
+ (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
+ ts.isInternalDeclaration(node, currentSourceFile) &&
+ sourceFileTextKind !== "internal" /* Internal */) {
+ var prevSourceFileTextKind = sourceFileTextKind;
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = "internal" /* Internal */;
+ return prevSourceFileTextKind;
+ }
+ return undefined;
+ }
+ function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
+ if (prevSourceFileTextKind) {
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = prevSourceFileTextKind;
+ }
+ }
+ function recordBundleFileTextLikeSection(end) {
+ if (sourceFileTextPos < end) {
+ updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
+ return true;
+ }
+ return false;
+ }
+ function writeBundle(bundle, output, sourceMapGenerator) {
+ var _a;
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output, sourceMapGenerator);
@@ -82331,18 +83682,49 @@
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
- var prepend = _b[_a];
+ for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
+ var prepend = _c[_b];
writeLine();
+ var pos = writer.getTextPos();
+ var savedSections = bundleFileInfo && bundleFileInfo.sections;
+ if (savedSections)
+ bundleFileInfo.sections = [];
print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
+ if (bundleFileInfo) {
+ var newSections = bundleFileInfo.sections;
+ bundleFileInfo.sections = savedSections;
+ if (prepend.oldFileOfCurrentEmit)
+ (_a = bundleFileInfo.sections).push.apply(_a, newSections);
+ else {
+ newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prepend" /* Prepend */, data: prepend.fileName, texts: newSections });
}
- if (bundleInfo) {
- bundleInfo.originalOffset = writer.getTextPos();
}
- for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
- var sourceFile = _d[_c];
+ }
+ sourceFileTextPos = getTextPosWithWriteLine();
+ for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
+ var sourceFile = _e[_d];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
+ if (bundleFileInfo && bundle.sourceFiles.length) {
+ var end = writer.getTextPos();
+ if (recordBundleFileTextLikeSection(end)) {
+ // Store prologues
+ var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
+ if (prologues) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.prologues = prologues;
+ }
+ // Store helpes
+ var helpers = getHelpersFromBundledSourceFiles(bundle);
+ if (helpers) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.helpers = helpers;
+ }
+ }
+ }
reset();
writer = previousWriter;
}
@@ -82412,8 +83794,10 @@
function emit(node) {
if (node === undefined)
return;
+ var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
pipelinePhase(4 /* Unspecified */, node);
+ recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
}
function emitIdentifierName(node) {
if (node === undefined)
@@ -82440,12 +83824,12 @@
}
// falls through
case 2 /* Comments */:
- if (!commentsDisabled && node.kind !== 279 /* SourceFile */) {
+ if (!commentsDisabled && node.kind !== 284 /* SourceFile */) {
return pipelineEmitWithComments;
}
// falls through
case 3 /* SourceMaps */:
- if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) {
+ if (!sourceMapsDisabled && node.kind !== 284 /* SourceFile */ && !ts.isInJsonFile(node)) {
return pipelineEmitWithSourceMap;
}
// falls through
@@ -82482,8 +83866,16 @@
case 16 /* TemplateMiddle */:
case 17 /* TemplateTail */:
return emitLiteral(node);
- case 281 /* UnparsedSource */:
- return emitUnparsedSource(node);
+ case 286 /* UnparsedSource */:
+ case 280 /* UnparsedPrepend */:
+ return emitUnparsedSourceOrPrepend(node);
+ case 279 /* UnparsedPrologue */:
+ return writeUnparsedNode(node);
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return emitUnparsedTextLike(node);
+ case 283 /* UnparsedSyntheticReference */:
+ return emitUnparsedSyntheticReference(node);
// Identifiers
case 72 /* Identifier */:
return emitIdentifier(node);
@@ -82527,7 +83919,7 @@
return emitTypeReference(node);
case 165 /* FunctionType */:
return emitFunctionType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return emitJSDocFunctionType(node);
case 166 /* ConstructorType */:
return emitConstructorType(node);
@@ -82565,20 +83957,20 @@
return emitLiteralType(node);
case 183 /* ImportType */:
return emitImportTypeNode(node);
- case 284 /* JSDocAllType */:
+ case 289 /* JSDocAllType */:
writePunctuation("*");
return;
- case 285 /* JSDocUnknownType */:
+ case 290 /* JSDocUnknownType */:
writePunctuation("?");
return;
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return emitJSDocNullableType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return emitJSDocNonNullableType(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return emitJSDocOptionalType(node);
case 172 /* RestType */:
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return emitRestOrJSDocVariadicType(node);
// Binding patterns
case 184 /* ObjectBindingPattern */:
@@ -82716,30 +84108,30 @@
case 278 /* EnumMember */:
return emitEnumMember(node);
// JSDoc nodes (only used in codefixes currently)
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return emitJSDocPropertyLikeTag(node);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return emitJSDocSimpleTypedTag(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return emitJSDocAugmentsTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return emitJSDocTemplateTag(node);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return emitJSDocTypedefTag(node);
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return emitJSDocCallbackTag(node);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return emitJSDocSignature(node);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return emitJSDocTypeLiteral(node);
- case 296 /* JSDocClassTag */:
- case 294 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
return emitJSDocSimpleTag(node);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return emitJSDoc(node);
// Transformation nodes (ignored)
}
@@ -82838,9 +84230,9 @@
case 264 /* JsxFragment */:
return emitJsxFragment(node);
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return emitPartiallyEmittedExpression(node);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return emitCommaList(node);
}
}
@@ -82856,22 +84248,45 @@
var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node);
pipelinePhase(hint, substituteNode(hint, node));
}
+ function getHelpersFromBundledSourceFiles(bundle) {
+ var result;
+ if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
+ return undefined;
+ }
+ var bundledHelpers = ts.createMap();
+ for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
+ var helpers = getSortedEmitHelpers(sourceFile);
+ if (!helpers)
+ continue;
+ for (var _c = 0, helpers_3 = helpers; _c < helpers_3.length; _c++) {
+ var helper = helpers_3[_c];
+ if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
+ bundledHelpers.set(helper.name, true);
+ (result || (result = [])).push(helper.name);
+ }
+ }
+ }
+ return result;
+ }
function emitHelpers(node) {
var helpersEmitted = false;
- var bundle = node.kind === 280 /* Bundle */ ? node : undefined;
+ var bundle = node.kind === 285 /* Bundle */ ? node : undefined;
if (bundle && moduleKind === ts.ModuleKind.None) {
return;
}
- var numNodes = bundle ? bundle.sourceFiles.length : 1;
+ var numPrepends = bundle ? bundle.prepends.length : 0;
+ var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
for (var i = 0; i < numNodes; i++) {
- var currentNode = bundle ? bundle.sourceFiles[i] : node;
- var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile;
- var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined;
- var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit;
- var helpers = ts.getEmitHelpers(currentNode);
+ var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
+ var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
+ var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
+ var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
+ var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
if (helpers) {
- for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
- var helper = _b[_a];
+ for (var _a = 0, helpers_4 = helpers; _a < helpers_4.length; _a++) {
+ var helper = helpers_4[_a];
if (!helper.scoped) {
// Skip the helper if it can be skipped and the noEmitHelpers compiler
// option is set, or if it can be imported and the importHelpers compiler
@@ -82891,18 +84306,25 @@
// Skip the helper if it is scoped and we are emitting bundled helpers
continue;
}
+ var pos = getTextPosWithWriteLine();
if (typeof helper.text === "string") {
writeLines(helper.text);
}
else {
writeLines(helper.text(makeFileLevelOptimisticUniqueName));
}
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
helpersEmitted = true;
}
}
}
return helpersEmitted;
}
+ function getSortedEmitHelpers(node) {
+ var helpers = ts.getEmitHelpers(node);
+ return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
+ }
//
// Literals/Pseudo-literals
//
@@ -82929,8 +84351,42 @@
}
}
// SyntaxKind.UnparsedSource
- function emitUnparsedSource(unparsed) {
- writer.rawWrite(unparsed.text);
+ // SyntaxKind.UnparsedPrepend
+ function emitUnparsedSourceOrPrepend(unparsed) {
+ for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
+ var text = _b[_a];
+ writeLine();
+ emit(text);
+ }
+ }
+ // SyntaxKind.UnparsedPrologue
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ // SyntaxKind.UnparsedSyntheticReference
+ function writeUnparsedNode(unparsed) {
+ writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
+ }
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ function emitUnparsedTextLike(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 281 /* UnparsedText */ ?
+ "text" /* Text */ :
+ "internal" /* Internal */);
+ }
+ }
+ // SyntaxKind.UnparsedSyntheticReference
+ function emitUnparsedSyntheticReference(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ var section = ts.clone(unparsed.section);
+ section.pos = pos;
+ section.end = writer.getTextPos();
+ bundleFileInfo.sections.push(section);
+ }
}
//
// Identifiers
@@ -82985,7 +84441,7 @@
emit(node.dotDotDotToken);
emitNodeWithWriter(node.name, writeParameter);
emit(node.questionToken);
- if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) {
+ if (node.parent && node.parent.kind === 294 /* JSDocFunctionType */ && !node.name) {
emit(node.type);
}
else {
@@ -83865,7 +85321,7 @@
}
function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
// Emit all the prologue directives (like "use strict").
- var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true);
+ var statementOffset = emitPrologueDirectives(body.statements);
var pos = writer.getTextPos();
emitHelpers(body);
if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
@@ -84125,7 +85581,7 @@
writePunctuation(">");
}
function emitJsxText(node) {
- writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true));
+ writer.writeLiteral(node.text);
}
function emitJsxClosingElementOrFragment(node) {
writePunctuation("</");
@@ -84270,7 +85726,7 @@
}
}
if (node.tags) {
- if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) {
+ if (node.tags.length === 1 && node.tags[0].kind === 307 /* JSDocTypeTag */ && !node.comment) {
writeSpace();
emit(node.tags[0]);
}
@@ -84304,7 +85760,7 @@
function emitJSDocTypedefTag(tag) {
emitJSDocTagName(tag.tagName);
if (tag.typeExpression) {
- if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
emitJSDocTypeExpression(tag.typeExpression);
}
else {
@@ -84323,7 +85779,7 @@
emit(tag.fullName);
}
emitJSDocComment(tag.comment);
- if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) {
+ if (tag.typeExpression && tag.typeExpression.kind === 297 /* JSDocTypeLiteral */) {
emitJSDocTypeLiteral(tag.typeExpression);
}
}
@@ -84410,6 +85866,16 @@
}
function emitSyntheticTripleSlashReferencesIfNeeded(node) {
emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
+ for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
+ for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
+ var ref = _d[_c];
+ emit(ref);
+ writeLine();
+ }
+ }
+ }
}
function emitTripleSlashDirectivesIfNeeded(node) {
if (node.isDeclarationFile)
@@ -84417,7 +85883,10 @@
}
function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
if (hasNoDefaultLib) {
+ var pos = writer.getTextPos();
writeComment("/// <reference no-default-lib=\"true\"/>");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
writeLine();
}
if (currentSourceFile && currentSourceFile.moduleName) {
@@ -84438,17 +85907,26 @@
}
for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
var directive = files_1[_c];
+ var pos = writer.getTextPos();
writeComment("/// <reference path=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
writeLine();
}
- for (var _d = 0, types_18 = types; _d < types_18.length; _d++) {
- var directive = types_18[_d];
+ for (var _d = 0, types_19 = types; _d < types_19.length; _d++) {
+ var directive = types_19[_d];
+ var pos = writer.getTextPos();
writeComment("/// <reference types=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
writeLine();
}
for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
var directive = libs_1[_e];
+ var pos = writer.getTextPos();
writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
writeLine();
}
}
@@ -84473,16 +85951,22 @@
* Emits any prologue directives at the start of a Statement list, returning the
* number of prologue directives written to the output.
*/
- function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) {
+ function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
+ var needsToSetSourceFile = !!sourceFile;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (ts.isPrologueDirective(statement)) {
var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
if (shouldEmitPrologueDirective) {
- if (startWithNewLine || i > 0) {
- writeLine();
+ if (needsToSetSourceFile) {
+ needsToSetSourceFile = false;
+ setSourceFile(sourceFile);
}
+ writeLine();
+ var pos = writer.getTextPos();
emit(statement);
+ if (recordBundleFileSection && bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
if (seenPrologueDirectives) {
seenPrologueDirectives.set(statement.expression.text, true);
}
@@ -84495,23 +85979,70 @@
}
return statements.length;
}
+ function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
+ for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
+ var prologue = prologues_1[_a];
+ if (!seenPrologueDirectives.has(prologue.data)) {
+ writeLine();
+ var pos = writer.getTextPos();
+ emit(prologue);
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
+ if (seenPrologueDirectives) {
+ seenPrologueDirectives.set(prologue.data, true);
+ }
+ }
+ }
+ }
function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
if (ts.isSourceFile(sourceFileOrBundle)) {
- setSourceFile(sourceFileOrBundle);
- emitPrologueDirectives(sourceFileOrBundle.statements);
+ emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
}
else {
var seenPrologueDirectives = ts.createMap();
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
- setSourceFile(sourceFile);
- emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
+ emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
}
setSourceFile(undefined);
}
}
+ function getPrologueDirectivesFromBundledSourceFiles(bundle) {
+ var seenPrologueDirectives = ts.createMap();
+ var prologues;
+ for (var index = 0; index < bundle.sourceFiles.length; index++) {
+ var sourceFile = bundle.sourceFiles[index];
+ var directives = void 0;
+ var end = 0;
+ for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
+ var statement = _b[_a];
+ if (!ts.isPrologueDirective(statement))
+ break;
+ if (seenPrologueDirectives.has(statement.expression.text))
+ continue;
+ seenPrologueDirectives.set(statement.expression.text, true);
+ (directives || (directives = [])).push({
+ pos: statement.pos,
+ end: statement.end,
+ expression: {
+ pos: statement.expression.pos,
+ end: statement.expression.end,
+ text: statement.expression.text
+ }
+ });
+ end = end < statement.end ? statement.end : end;
+ }
+ if (directives)
+ (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
+ }
+ return prologues;
+ }
function emitShebangIfNeeded(sourceFileOrBundle) {
- if (ts.isSourceFile(sourceFileOrBundle)) {
+ if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
var shebang = ts.getShebang(sourceFileOrBundle.text);
if (shebang) {
writeComment(shebang);
@@ -84520,11 +86051,18 @@
}
}
else {
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ ts.Debug.assertNode(prepend, ts.isUnparsedSource);
+ if (emitShebangIfNeeded(prepend)) {
+ return true;
+ }
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
// Emit only the first encountered shebang
if (emitShebangIfNeeded(sourceFile)) {
- break;
+ return true;
}
}
}
@@ -84727,6 +86265,7 @@
}
// Emit each child.
var previousSibling = void 0;
+ var previousSourceFileTextKind = void 0;
var shouldDecreaseIndentAfterEmit = false;
for (var i = 0; i < count; i++) {
var child = children[start + i];
@@ -84747,6 +86286,7 @@
emitLeadingCommentsOfPosition(previousSibling.end);
}
writeDelimiter(format);
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write either a line terminator or whitespace to separate the elements.
if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
// If a synthesized node in a single-line list starts on a new
@@ -84763,6 +86303,7 @@
}
}
// Emit this child.
+ previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
if (shouldEmitInterveningComments) {
if (emitTrailingCommentsOfPosition) {
var commentRange = ts.getCommentRange(child);
@@ -84797,6 +86338,7 @@
if (format & 128 /* Indented */) {
decreaseIndent();
}
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write the closing line terminator or closing whitespace.
if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
writeLine();
@@ -84898,7 +86440,6 @@
if (line.length) {
writeLine();
write(line);
- writer.rawWrite(newLine);
}
}
}
@@ -85412,7 +86953,7 @@
hasWrittenComment = false;
var emitFlags = ts.getEmitFlags(node);
var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
- var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 312 /* 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 === 11 /* JsxText */;
@@ -85672,19 +87213,28 @@
return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
}
// Source Maps
+ function getParsedSourceMap(node) {
+ if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
+ node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
+ }
+ return node.parsedSourceMap || undefined;
+ }
function pipelineEmitWithSourceMap(hint, node) {
var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node);
- if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) {
- var parsed = ts.tryParseRawSourceMap(node.sourceMapText);
- if (parsed) {
- sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath);
+ if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
+ pipelinePhase(hint, node);
+ }
+ else if (ts.isUnparsedNode(node)) {
+ var parsed = getParsedSourceMap(node.parent);
+ if (parsed && sourceMapGenerator) {
+ sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
}
pipelinePhase(hint, node);
}
else {
var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
var emitFlags = ts.getEmitFlags(node);
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitSourcePos(source, skipSourceTrivia(source, pos));
@@ -85697,7 +87247,7 @@
else {
pipelinePhase(hint, node);
}
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitSourcePos(source, end);
@@ -85825,7 +87375,8 @@
writeFile: host.writeFile && writeFile,
addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
addOrDeleteFile: addOrDeleteFile,
- clearCache: clearCache
+ clearCache: clearCache,
+ realpath: host.realpath && realpath
};
function toPath(fileName) {
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
@@ -85922,7 +87473,7 @@
var rootDirPath = toPath(rootDir);
var result = tryReadDirectory(rootDir, rootDirPath);
if (result) {
- return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries);
+ return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
}
return host.readDirectory(rootDir, extensions, excludes, includes, depth);
function getFileSystemEntries(dir) {
@@ -85933,6 +87484,9 @@
return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
}
}
+ function realpath(s) {
+ return host.realpath ? host.realpath(s) : s;
+ }
function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
if (existingResult) {
@@ -86203,11 +87757,7 @@
function createCompilerHostWorker(options, setParentNodes, system) {
if (system === void 0) { system = ts.sys; }
var existingDirectories = ts.createMap();
- function getCanonicalFileName(fileName) {
- // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
- // otherwise use toLowerCase as a canonical form.
- return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
- }
+ var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
function getSourceFile(fileName, languageVersion, onError) {
var text;
try {
@@ -86332,20 +87882,21 @@
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
- return value || undefined;
+ return value !== false ? value : undefined;
return setReadFileCache(key, fileName);
};
var setReadFileCache = function (key, fileName) {
var newValue = originalReadFile.call(host, fileName);
- readFileCache.set(key, newValue || false);
+ readFileCache.set(key, newValue !== undefined ? newValue : false);
return newValue;
};
host.readFile = function (fileName) {
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
- return value; // could be .d.ts from output
- if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ return value !== false ? value : undefined; // could be .d.ts from output
+ // Cache json or buildInfo
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
return originalReadFile.call(host, fileName);
}
return setReadFileCache(key, fileName);
@@ -86376,7 +87927,7 @@
var key = toPath(fileName);
fileExistsCache.delete(key);
var value = readFileCache.get(key);
- if (value && value !== data) {
+ if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.delete(key);
}
@@ -86822,11 +88373,18 @@
if (rootNames.length) {
for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
var parsedRef = resolvedProjectReferences_1[_i];
- if (parsedRef) {
+ if (!parsedRef)
+ continue;
var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
if (out) {
- var dtsOutfile = ts.changeExtension(out, ".d.ts");
- processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ }
+ else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
+ for (var _a = 0, _b = parsedRef.commandLine.fileNames; _a < _b.length; _a++) {
+ var fileName = _b[_a];
+ if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(fileName)) {
+ processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ }
}
}
}
@@ -86874,8 +88432,8 @@
// not part of the new program.
if (oldProgram && host.onReleaseOldSourceFile) {
var oldSourceFiles = oldProgram.getSourceFiles();
- for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) {
- var oldSourceFile = oldSourceFiles_1[_a];
+ for (var _c = 0, oldSourceFiles_1 = oldSourceFiles; _c < oldSourceFiles_1.length; _c++) {
+ var oldSourceFile = oldSourceFiles_1[_c];
var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
if (shouldCreateNewSourceFile || !newFile ||
// old file wasnt redirect but new file is
@@ -86931,7 +88489,8 @@
getProjectReferenceRedirect: getProjectReferenceRedirect,
getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
- forEachResolvedProjectReference: forEachResolvedProjectReference
+ forEachResolvedProjectReference: forEachResolvedProjectReference,
+ emitBuildInfo: emitBuildInfo
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -86960,7 +88519,7 @@
}
function getCommonSourceDirectory() {
if (commonSourceDirectory === undefined) {
- var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); });
+ var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
// If a rootDir is specified use it as the commonSourceDirectory
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
@@ -87349,7 +88908,8 @@
}
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, getLibFileFromReference: program.getLibFileFromReference, 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) {
+ 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, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
+ getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, 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))
@@ -87358,7 +88918,20 @@
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(); } });
+ } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); } });
+ }
+ function emitBuildInfo(writeFileCallback) {
+ ts.Debug.assert(!options.out && !options.outFile);
+ ts.performance.mark("beforeEmit");
+ var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback),
+ /*targetSourceFile*/ undefined,
+ /*emitOnlyDtsFiles*/ false,
+ /*transformers*/ undefined,
+ /*declaraitonTransformers*/ undefined,
+ /*onlyBuildInfo*/ true);
+ ts.performance.mark("afterEmit");
+ ts.performance.measure("Emit", "beforeEmit", "afterEmit");
+ return emitResult;
}
function getResolvedProjectReferences() {
return resolvedProjectReferences;
@@ -87367,28 +88940,11 @@
return projectReferences;
}
function getPrependNodes() {
- if (!projectReferences) {
- return ts.emptyArray;
- }
- var nodes = [];
- for (var i = 0; i < projectReferences.length; i++) {
- var ref = projectReferences[i];
- var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
- if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
- var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
- // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
- if (!out)
- continue;
- var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- var node = ts.createInputFiles(function (fileName) {
+ return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
var path = toPath(fileName);
var sourceFile = getSourceFileByPath(path);
return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
- }, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath);
- nodes.push(node);
- }
- }
- return nodes;
+ });
}
function isSourceFileFromExternalLibrary(file) {
return !!sourceFilesFoundSearchingNodeModules.get(file.path);
@@ -87460,8 +89016,7 @@
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
ts.performance.mark("beforeEmit");
var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217
- emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -88073,7 +89628,6 @@
if (refFile) {
var redirect = getProjectReferenceRedirect(fileName);
if (redirect) {
- (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName);
fileName = redirect;
// Once we start redirecting to a file, we can potentially come back to it
// via a back-reference from another file in the .d.ts folder. If that happens we'll
@@ -88170,7 +89724,7 @@
var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
return out ?
ts.changeExtension(out, ".d.ts" /* Dts */) :
- ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine);
+ ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
}
/**
* Get the referenced project if the file is input file from that reference project
@@ -88463,18 +90017,29 @@
if (options.declaration === false) {
createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
}
+ if (options.incremental === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
+ }
+ }
+ if (options.tsBuildInfoFile) {
+ if (!ts.isIncrementalCompilation(options)) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
+ }
}
verifyProjectReferences();
// List of collected files is complete; validate exhautiveness if this is a project with a file list
if (options.composite) {
- var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; });
- if (rootNames.length < sourceFiles.length) {
- var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); });
- for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) {
- var file = _a[_i];
- if (normalizedRootNames.indexOf(file) === -1) {
- 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));
- }
+ var rootPaths = rootNames.map(toPath);
+ for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
+ var file = files_3[_i];
+ // Ignore declaration files
+ if (file.isDeclarationFile)
+ continue;
+ // Ignore json file thats from project reference
+ if (ts.isJsonSourceFile(file) && getResolvedProjectReferenceToRedirect(file.fileName))
+ continue;
+ if (rootPaths.indexOf(file.path) === -1) {
+ 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.fileName));
}
}
}
@@ -88657,6 +90222,7 @@
}
}
function verifyProjectReferences() {
+ var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getOutputPathForBuildInfo(options) : undefined;
forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
var parentFile = parent && parent.sourceFile;
@@ -88683,6 +90249,10 @@
createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
}
}
+ if (!parent && buildInfoPath && buildInfoPath === ts.getOutputPathForBuildInfo(options)) {
+ createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
+ hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
+ }
});
}
function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
@@ -88827,11 +90397,32 @@
readFile: function (f) { return directoryStructureHost.readFile(f); },
useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
getCurrentDirectory: function () { return host.getCurrentDirectory(); },
- onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || (function () { return undefined; }),
+ onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
trace: host.trace ? function (s) { return host.trace(s); } : undefined
};
}
ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
+ /* @internal */
+ function createPrependNodes(projectReferences, getCommandLine, readFile) {
+ if (!projectReferences)
+ return ts.emptyArray;
+ var nodes;
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = getCommandLine(ref, i);
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!out)
+ continue;
+ var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
+ (nodes || (nodes = [])).push(node);
+ }
+ }
+ return nodes || ts.emptyArray;
+ }
+ ts.createPrependNodes = createPrependNodes;
function resolveProjectReferencePath(hostOrRef, ref) {
var passedInRef = ref ? ref : hostOrRef;
return ts.resolveConfigFileProjectName(passedInRef.path);
@@ -89028,7 +90619,7 @@
// Create the reference map, and set the file infos
for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
- var version_1 = sourceFile.version;
+ var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined;
if (referencedMap) {
var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
@@ -89083,9 +90674,9 @@
*/
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
+ // They will be committed once it is safe to use them
// eg when calling this api from tsserver, if there is no cancellation of the operation
- // In the other cases the affected files signatures are commited only after the iteration through the result is complete
+ // In the other cases the affected files signatures are committed only after the iteration through the result is complete
var signatureCache = cacheToUpdateSignature || ts.createMap();
var sourceFile = programOfThisState.getSourceFileByPath(path);
if (!sourceFile) {
@@ -89375,11 +90966,14 @@
var affectedSignatures = oldState.currentAffectedFilesSignatures;
ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
}
+ var changedFilesSet = oldState.changedFilesSet;
if (canCopySemanticDiagnostics) {
- ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
+ ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
}
// Copy old state's changed files set
- ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet);
+ if (changedFilesSet) {
+ ts.copyEntries(changedFilesSet, state.changedFilesSet);
+ }
if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit;
state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
@@ -89417,7 +91011,7 @@
// Unchanged file copy diagnostics
var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
if (diagnostics) {
- state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics);
+ state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics);
if (!state.semanticDiagnosticsFromOldState) {
state.semanticDiagnosticsFromOldState = ts.createMap();
}
@@ -89425,8 +91019,45 @@
}
}
});
+ if (oldCompilerOptions &&
+ (oldCompilerOptions.outDir !== compilerOptions.outDir ||
+ oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
+ (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
+ // Add all files to affectedFilesPendingEmit since emit changed
+ state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(function (f) { return f.path; }));
+ if (state.affectedFilesPendingEmitIndex === undefined) {
+ state.affectedFilesPendingEmitIndex = 0;
+ }
+ ts.Debug.assert(state.seenAffectedFiles === undefined);
+ state.seenAffectedFiles = ts.createMap();
+ }
return state;
}
+ function convertToDiagnostics(diagnostics, newProgram) {
+ if (!diagnostics.length)
+ return ts.emptyArray;
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToDiagnosticRelatedInformation(diagnostic, newProgram) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && newProgram.getSourceFileByPath(file), messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToDiagnosticMessageChain(messageText, newProgram) });
+ }
+ function convertToDiagnosticMessageChain(diagnostic, newProgram) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram) });
+ }
/**
* Releases program and other related not needed properties
*/
@@ -89646,8 +91277,11 @@
* 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
*/
- function doneWithAffectedFile(state, affected, isPendingEmit) {
- if (affected === state.program) {
+ function doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit) {
+ if (isBuildInfoEmit) {
+ state.emittedBuildInfo = true;
+ }
+ else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
@@ -89664,8 +91298,8 @@
/**
* Returns the result with affected file
*/
- function toAffectedFileResult(state, result, affected, isPendingEmit) {
- doneWithAffectedFile(state, affected, isPendingEmit);
+ function toAffectedFileResult(state, result, affected, isPendingEmit, isBuildInfoEmit) {
+ doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
return { result: result, affected: affected };
}
/**
@@ -89688,6 +91322,77 @@
}
return diagnostics;
}
+ /**
+ * Gets the program information to be emitted in buildInfo so that we can use it to create new program
+ */
+ function getProgramBuildInfo(state) {
+ if (state.compilerOptions.outFile || state.compilerOptions.out)
+ return undefined;
+ var fileInfos = {};
+ state.fileInfos.forEach(function (value, key) {
+ var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
+ fileInfos[key] = signature === undefined ? value : { version: value.version, signature: signature };
+ });
+ var result = { fileInfos: fileInfos, options: state.compilerOptions };
+ if (state.referencedMap) {
+ var referencedMap_1 = {};
+ state.referencedMap.forEach(function (value, key) {
+ referencedMap_1[key] = ts.arrayFrom(value.keys());
+ });
+ result.referencedMap = referencedMap_1;
+ }
+ if (state.exportedModulesMap) {
+ var exportedModulesMap_1 = {};
+ state.exportedModulesMap.forEach(function (value, key) {
+ var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
+ // Not in temporary cache, use existing value
+ if (newValue === undefined)
+ exportedModulesMap_1[key] = ts.arrayFrom(value.keys());
+ // Value in cache and has updated value map, use that
+ else if (newValue)
+ exportedModulesMap_1[key] = ts.arrayFrom(newValue.keys());
+ });
+ result.exportedModulesMap = exportedModulesMap_1;
+ }
+ if (state.semanticDiagnosticsPerFile) {
+ var semanticDiagnosticsPerFile_1 = [];
+ // Currently not recording actual errors since those mean no emit for tsc --build
+ state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ?
+ [
+ key,
+ state.hasReusableDiagnostic ?
+ value :
+ convertToReusableDiagnostics(value)
+ ] :
+ key); });
+ result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1;
+ }
+ return result;
+ }
+ function convertToReusableDiagnostics(diagnostics) {
+ ts.Debug.assert(!!diagnostics.length);
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToReusableDiagnosticRelatedInformation(diagnostic);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToReusableDiagnosticRelatedInformation(diagnostic) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && file.path, messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToReusableDiagnosticMessageChain(messageText) });
+ }
+ function convertToReusableDiagnosticMessageChain(diagnostic) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next) });
+ }
var BuilderProgramKind;
(function (BuilderProgramKind) {
BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
@@ -89744,6 +91449,7 @@
var computeHash = host.createHash || ts.generateDjb2Hash;
var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
var backupState;
+ newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state); };
// To ensure that we arent storing any references to old program or new program without state
newProgram = undefined; // TODO: GH#18217
oldProgram = undefined;
@@ -89787,8 +91493,17 @@
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
affected = getNextAffectedFilePendingEmit(state);
if (!affected) {
+ if (state.emittedBuildInfo) {
return undefined;
}
+ var affected_1 = ts.Debug.assertDefined(state.program);
+ return toAffectedFileResult(state,
+ // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
+ // Otherwise just affected file
+ affected_1.emitBuildInfo(writeFile || host.writeFile, cancellationToken), affected_1,
+ /*isPendingEmitFile*/ false,
+ /*isBuildInfoEmit*/ true);
+ }
isPendingEmitFile = true;
}
else {
@@ -89913,13 +91628,60 @@
}
var diagnostics;
for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
- var sourceFile_2 = _a[_i];
- diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken));
+ var sourceFile_1 = _a[_i];
+ diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
}
return diagnostics || ts.emptyArray;
}
}
ts.createBuilderProgram = createBuilderProgram;
+ function getMapOfReferencedSet(mapLike) {
+ if (!mapLike)
+ return undefined;
+ var map = ts.createMap();
+ // Copies keys/values from template. Note that for..in will not throw if
+ // template is undefined, and instead will just exit the loop.
+ for (var key in mapLike) {
+ if (ts.hasProperty(mapLike, key)) {
+ map.set(key, ts.arrayToSet(mapLike[key]));
+ }
+ }
+ return map;
+ }
+ function createBuildProgramUsingProgramBuildInfo(program) {
+ var fileInfos = ts.createMapFromTemplate(program.fileInfos);
+ var state = {
+ fileInfos: fileInfos,
+ compilerOptions: program.options,
+ referencedMap: getMapOfReferencedSet(program.referencedMap),
+ exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
+ semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return ts.isString(value) ? value : value[0]; }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
+ hasReusableDiagnostic: true
+ };
+ return {
+ getState: function () { return state; },
+ backupState: ts.noop,
+ restoreState: ts.noop,
+ getProgram: ts.notImplemented,
+ getProgramOrUndefined: ts.returnUndefined,
+ releaseProgram: ts.noop,
+ getCompilerOptions: function () { return state.compilerOptions; },
+ getSourceFile: ts.notImplemented,
+ getSourceFiles: ts.notImplemented,
+ getOptionsDiagnostics: ts.notImplemented,
+ getGlobalDiagnostics: ts.notImplemented,
+ getConfigFileParsingDiagnostics: ts.notImplemented,
+ getSyntacticDiagnostics: ts.notImplemented,
+ getDeclarationDiagnostics: ts.notImplemented,
+ getSemanticDiagnostics: ts.notImplemented,
+ emit: ts.notImplemented,
+ getAllDependencies: ts.notImplemented,
+ getCurrentDirectory: ts.notImplemented,
+ emitNextAffectedFile: ts.notImplemented,
+ getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
+ };
+ }
+ ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
return {
getState: ts.notImplemented,
@@ -89939,7 +91701,7 @@
getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
getAllDependencies: ts.notImplemented,
- getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); }
+ getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
};
function getProgram() {
return ts.Debug.assertDefined(state.program);
@@ -89965,10 +91727,10 @@
/*@internal*/
var ts;
(function (ts) {
- function isPathInNodeModulesStartingWithDot(path) {
- return ts.stringContains(path, "/node_modules/.");
+ function isPathIgnored(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); });
}
- ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot;
+ ts.isPathIgnored = isPathIgnored;
ts.maxNumberOfFilesToIterateForInvalidation = 256;
function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
var filesWithChangedSetOfUnresolvedImports;
@@ -90490,7 +92252,7 @@
}
else {
// If something to do with folder/file starting with "." in node_modules folder, skip it
- if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (isPathIgnored(fileOrDirectoryPath))
return false;
// Some file or directory in the watching directory is created
// Return early if it does not have any of the watching extension or not the custom failed lookup path
@@ -90967,6 +92729,8 @@
case ".jsx" /* Jsx */:
case ".json" /* Json */:
return ext;
+ case ".tsbuildinfo" /* TsBuildInfo */:
+ return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
default:
return ts.Debug.assertNever(ext);
}
@@ -91087,22 +92851,18 @@
var diagnostics = program.getConfigFileParsingDiagnostics().slice();
var configFileParsingDiagnosticsLength = diagnostics.length;
ts.addRange(diagnostics, program.getSyntacticDiagnostics());
- var reportSemanticDiagnostics = false;
// If we didn't have any syntactic errors, then also try getting the global and
// semantic errors.
if (diagnostics.length === configFileParsingDiagnosticsLength) {
ts.addRange(diagnostics, program.getOptionsDiagnostics());
ts.addRange(diagnostics, program.getGlobalDiagnostics());
if (diagnostics.length === configFileParsingDiagnosticsLength) {
- reportSemanticDiagnostics = true;
+ ts.addRange(diagnostics, program.getSemanticDiagnostics());
}
}
// Emit and report any errors we ran into.
var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics;
ts.addRange(diagnostics, emitDiagnostics);
- if (reportSemanticDiagnostics) {
- ts.addRange(diagnostics, program.getSemanticDiagnostics());
- }
ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic);
if (writeFileName) {
var currentDir_1 = program.getCurrentDirectory();
@@ -91223,6 +92983,22 @@
}
}
ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
+ function setGetSourceFileAsHashVersioned(compilerHost, host) {
+ var originalGetSourceFile = compilerHost.getSourceFile;
+ var computeHash = host.createHash || ts.generateDjb2Hash;
+ compilerHost.getSourceFile = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
+ if (result) {
+ result.version = computeHash.call(host, result.text);
+ }
+ return result;
+ };
+ }
+ ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
/**
* Creates the watch compiler host that can be extended with config file or root file names and options host
*/
@@ -91248,7 +93024,7 @@
writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
createHash: ts.maybeBind(system, system.createHash),
- createProgram: createProgram
+ createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
};
}
ts.createProgramHost = createProgramHost;
@@ -91258,7 +93034,7 @@
function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
var writeFileName = function (s) { return system.write(s + system.newLine); };
- var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram);
+ var result = createProgramHost(system, createProgram);
ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = function (builderProgram) {
var compilerOptions = builderProgram.getCompilerOptions();
@@ -91297,6 +93073,49 @@
return host;
}
ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
+ function readBuilderProgram(compilerOptions, readFile) {
+ if (compilerOptions.out || compilerOptions.outFile)
+ return undefined;
+ var buildInfoPath = ts.getOutputPathForBuildInfo(compilerOptions);
+ if (!buildInfoPath)
+ return undefined;
+ var content = readFile(buildInfoPath);
+ if (!content)
+ return undefined;
+ var buildInfo = ts.getBuildInfo(content);
+ if (buildInfo.version !== ts.version)
+ return undefined;
+ if (!buildInfo.program)
+ return undefined;
+ return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program);
+ }
+ ts.readBuilderProgram = readBuilderProgram;
+ function createIncrementalCompilerHost(options, system) {
+ if (system === void 0) { system = ts.sys; }
+ var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
+ host.createHash = ts.maybeBind(system, system.createHash);
+ setGetSourceFileAsHashVersioned(host, system);
+ ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
+ return host;
+ }
+ ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
+ function createIncrementalProgram(_a) {
+ var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
+ host = host || createIncrementalCompilerHost(options);
+ createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
+ var oldProgram = readBuilderProgram(options, function (path) { return host.readFile(path); });
+ return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
+ }
+ function performIncrementalCompilation(input) {
+ var system = input.system || ts.sys;
+ var host = input.host || (input.host = createIncrementalCompilerHost(input.options, system));
+ var builderProgram = createIncrementalProgram(input);
+ var exitStatus = emitFilesAndReportErrors(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined);
+ if (input.afterProgramEmitAndDiagnostics)
+ input.afterProgramEmitAndDiagnostics(builderProgram);
+ return exitStatus;
+ }
+ ts.performIncrementalCompilation = performIncrementalCompilation;
})(ts || (ts = {}));
(function (ts) {
function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) {
@@ -91308,7 +93127,6 @@
}
}
ts.createWatchCompilerHost = createWatchCompilerHost;
- var initialVersion = 1;
function createWatchProgram(host) {
var builderProgram;
var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
@@ -91349,10 +93167,12 @@
var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
+ var configFileWatcher;
if (configFileName) {
- watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */);
+ configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */);
}
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
+ ts.setGetSourceFileAsHashVersioned(compilerHost, host);
// Members for CompilerHost
var getNewSourceFile = compilerHost.getSourceFile;
compilerHost.getSourceFile = function (fileName) {
@@ -91393,21 +93213,43 @@
(function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) :
(function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
+ builderProgram = ts.readBuilderProgram(compilerOptions, function (path) { return compilerHost.readFile(path); });
synchronizeProgram();
// Update the wild card directory watch
watchConfigFileWildCardDirectories();
return configFileName ?
- { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } :
- { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames };
+ { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } :
+ { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close };
+ function close() {
+ resolutionCache.clear();
+ ts.clearMap(sourceFilesCache, function (value) {
+ if (value && value.fileWatcher) {
+ value.fileWatcher.close();
+ value.fileWatcher = undefined;
+ }
+ });
+ if (configFileWatcher) {
+ configFileWatcher.close();
+ configFileWatcher = undefined;
+ }
+ if (watchedWildcardDirectories) {
+ ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
+ watchedWildcardDirectories = undefined;
+ }
+ if (missingFilesMap) {
+ ts.clearMap(missingFilesMap, ts.closeFileWatcher);
+ missingFilesMap = undefined;
+ }
+ }
function getCurrentBuilderProgram() {
return builderProgram;
}
function getCurrentProgram() {
- return builderProgram && builderProgram.getProgram();
+ return builderProgram && builderProgram.getProgramOrUndefined();
}
function synchronizeProgram() {
writeLog("Synchronizing program");
- var program = getCurrentProgram();
+ var program = getCurrentBuilderProgram();
if (hasChangedCompilerOptions) {
newLine = updateNewLine();
if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
@@ -91423,19 +93265,19 @@
}
}
else {
- createNewProgram(program, hasInvalidatedResolution);
+ createNewProgram(hasInvalidatedResolution);
}
if (host.afterProgramCreate) {
host.afterProgramCreate(builderProgram);
}
return builderProgram;
}
- function createNewProgram(program, hasInvalidatedResolution) {
+ function createNewProgram(hasInvalidatedResolution) {
// Compile the program
writeLog("CreatingProgramWith::");
writeLog(" roots: " + JSON.stringify(rootFileNames));
writeLog(" options: " + JSON.stringify(compilerOptions));
- var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program;
+ var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
hasChangedCompilerOptions = false;
hasChangedConfigFileParsingErrors = false;
resolutionCache.startCachingPerDirectoryResolution();
@@ -91475,10 +93317,10 @@
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
}
function isFileMissingOnHost(hostSourceFile) {
- return typeof hostSourceFile === "number";
+ return typeof hostSourceFile === "boolean";
}
- function isFilePresentOnHost(hostSourceFile) {
- return !!hostSourceFile.sourceFile;
+ function isFilePresenceUnknownOnHost(hostSourceFile) {
+ return typeof hostSourceFile.version === "boolean";
}
function fileExists(fileName) {
var path = toPath(fileName);
@@ -91496,36 +93338,32 @@
return undefined;
}
// Create new source file if requested or the versions dont match
- if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) {
+ if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
if (hostSourceFile) {
- if (shouldCreateNewSourceFile) {
- hostSourceFile.version++;
- }
if (sourceFile) {
// Set the source file and create file watcher now that file was present on the disk
hostSourceFile.sourceFile = sourceFile;
- sourceFile.version = hostSourceFile.version.toString();
+ hostSourceFile.version = sourceFile.version;
if (!hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */);
}
}
else {
// There is no source file on host any more, close the watch, missing file paths will track it
- if (isFilePresentOnHost(hostSourceFile)) {
+ if (hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher.close();
}
- sourceFilesCache.set(path, hostSourceFile.version);
+ sourceFilesCache.set(path, false);
}
}
else {
if (sourceFile) {
- sourceFile.version = initialVersion.toString();
var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */);
- sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher });
+ sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
}
else {
- sourceFilesCache.set(path, initialVersion);
+ sourceFilesCache.set(path, false);
}
}
return sourceFile;
@@ -91537,16 +93375,16 @@
if (hostSourceFile !== undefined) {
if (isFileMissingOnHost(hostSourceFile)) {
// The next version, lets set it as presence unknown file
- sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 });
+ sourceFilesCache.set(path, { version: false });
}
else {
- hostSourceFile.version++;
+ hostSourceFile.version = false;
}
}
}
function getSourceVersion(path) {
var hostSourceFile = sourceFilesCache.get(path);
- return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString();
+ return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
}
function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
@@ -91554,7 +93392,7 @@
// remove the cached entry.
// Note we arent deleting entry if file became missing in new program or
// there was version update and new source file was created.
- if (hostSourceFileInfo) {
+ if (hostSourceFileInfo !== undefined) {
// record the missing file paths so they can be removed later if watchers arent tracking them
if (isFileMissingOnHost(hostSourceFileInfo)) {
(missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
@@ -91643,7 +93481,7 @@
function onSourceFileChange(fileName, eventKind, path) {
updateCachedSystemWithFile(fileName, path, eventKind);
// Update the source file cache
- if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) {
+ if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
resolutionCache.invalidateResolutionOfFile(path);
}
resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
@@ -91687,7 +93525,7 @@
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
nextSourceFileVersion(fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
// 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
@@ -91741,16 +93579,23 @@
* This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
*/
UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
- UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream";
- UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate";
- UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked";
- UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream";
+ /**
+ * The project appears out of date because its upstream inputs are newer than its outputs,
+ * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
+ * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
+ */
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
+ UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
+ UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
+ UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
+ UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
+ UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
/**
* Projects with no outputs (i.e. "solution" files)
*/
- UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly";
+ UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
})(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
function createFileMap(toPath) {
// tslint:disable-next-line:no-null-keyword
@@ -91798,61 +93643,6 @@
function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
}
- 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);
- return ts.changeExtension(outputPath, ".d.ts" /* Dts */);
- }
- ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
- function getOutputJSFileName(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);
- 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) {
- // 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 = [];
- var js = getOutputJSFileName(inputFileName, configFile);
- outputs.push(js);
- if (configFile.options.sourceMap) {
- outputs.push(js + ".map");
- }
- 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");
- }
- }
- return outputs;
- }
- function getOutFileOutputs(project) {
- var out = project.options.outFile || project.options.out;
- if (!out) {
- return ts.Debug.fail("outFile must be set");
- }
- var outputs = [];
- outputs.push(out);
- if (project.options.sourceMap) {
- outputs.push(out + ".map");
- }
- if (ts.getEmitDeclarations(project.options)) {
- var dts = ts.changeExtension(out, ".d.ts" /* Dts */);
- outputs.push(dts);
- if (project.options.declarationMap) {
- outputs.push(dts + ".map");
- }
- }
- return outputs;
- }
- function rootDirOfOptions(opts, configFileName) {
- return opts.rootDir || ts.getDirectoryPath(configFileName);
- }
function newer(date1, date2) {
return date2 > date1 ? date2 : date1;
}
@@ -91872,7 +93662,7 @@
ts.createBuilderStatusReporter = createBuilderStatusReporter;
function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
var host = ts.createProgramHost(system, createProgram);
- host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; };
+ host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
@@ -91881,14 +93671,14 @@
}
function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
host.reportErrorSummary = reportErrorSummary;
return host;
}
ts.createSolutionBuilderHost = createSolutionBuilderHost;
function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
var watchHost = ts.createWatchHost(system, reportWatchStatus);
ts.copyProperties(host, watchHost);
return host;
@@ -91920,9 +93710,8 @@
var readFileWithCache = function (f) { return host.readFile(f); };
var projectCompilerOptions = baseCompilerOptions;
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; });
- var originalGetSourceFile = compilerHost.getSourceFile;
- var computeHash = host.createHash || ts.generateDjb2Hash;
- updateGetSourceFile();
+ ts.setGetSourceFileAsHashVersioned(compilerHost, host);
+ var buildInfoChecked = createFileMap(toPath);
// Watch state
var builderPrograms = createFileMap(toPath);
var diagnostics = createFileMap(toPath);
@@ -91960,6 +93749,7 @@
projectStatus.clear();
missingRoots.clear();
globalDependencyGraph = undefined;
+ buildInfoChecked.clear();
diagnostics.clear();
projectPendingBuild.clear();
projectErrorsReported.clear();
@@ -91974,29 +93764,6 @@
ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); });
ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher);
builderPrograms.clear();
- updateGetSourceFile();
- }
- function updateGetSourceFile() {
- if (options.watch) {
- if (compilerHost.getSourceFile === originalGetSourceFile) {
- compilerHost.getSourceFile = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
- if (result && options.watch) {
- result.version = computeHash.call(host, result.text);
- }
- return result;
- };
- }
- }
- else {
- if (compilerHost.getSourceFile !== originalGetSourceFile) {
- compilerHost.getSourceFile = originalGetSourceFile;
- }
- }
}
function isParsedCommandLine(entry) {
return !!entry.options;
@@ -92147,13 +93914,14 @@
newestInputFileTime = inputTime;
}
}
- // Collect the expected outputs of this project
- var outputs = getAllProjectOutputs(project);
- if (outputs.length === 0) {
+ // Container if no files are specified in the project
+ if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) {
return {
type: UpToDateStatusType.ContainerOnly
};
}
+ // Collect the expected outputs of this project
+ var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
// Now see if all outputs are newer than the newest input
var oldestOutputFileName = "(none)";
var oldestOutputFileTime = maximumDate;
@@ -92228,6 +93996,8 @@
upstreamProjectName: ref.path
};
}
+ // Check oldest output file name only if there is no missing output file name
+ if (!missingOutputFileName) {
// 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) {
@@ -92249,6 +94019,7 @@
};
}
}
+ }
if (missingOutputFileName !== undefined) {
return {
type: UpToDateStatusType.OutputMissing,
@@ -92262,9 +94033,33 @@
newerInputFileName: newestInputFileName
};
}
+ else {
+ // Check tsconfig time
+ var configStatus = checkConfigFileUpToDateStatus(project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
+ if (configStatus)
+ return configStatus;
+ // Check extended config time
+ var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName); });
+ if (extendedConfigStatus)
+ return extendedConfigStatus;
+ }
+ if (!buildInfoChecked.hasKey(project.options.configFilePath)) {
+ buildInfoChecked.setValue(project.options.configFilePath, true);
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath) {
+ var value = readFileWithCache(buildInfoPath);
+ var buildInfo = value && ts.getBuildInfo(value);
+ if (buildInfo && buildInfo.version !== ts.version) {
+ return {
+ type: UpToDateStatusType.TsVersionOutputOfDate,
+ version: buildInfo.version
+ };
+ }
+ }
+ }
if (usesPrepend && pseudoUpToDate) {
return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
+ type: UpToDateStatusType.OutOfDateWithPrepend,
outOfDateOutputFileName: oldestOutputFileName,
newerProjectName: upstreamChangedProject
};
@@ -92280,6 +94075,17 @@
oldestOutputFileName: oldestOutputFileName
};
}
+ function checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName) {
+ // Check tsconfig time
+ var tsconfigTime = host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
+ if (oldestOutputFileTime < tsconfigTime) {
+ return {
+ type: UpToDateStatusType.OutOfDateWithSelf,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerInputFileName: configFile
+ };
+ }
+ }
function invalidateProject(configFileName, reloadLevel) {
invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel);
}
@@ -92398,7 +94204,9 @@
updateOutputTimestamps(proj);
return;
}
- var buildResult = buildSingleProject(resolved);
+ var buildResult = needsBuild(status, resolved) ?
+ buildSingleProject(resolved) : // Actual build
+ updateBundle(resolved); // Fake that files have been built by manipulating prepend and existing output
if (buildResult & BuildResultFlags.AnyErrors)
return;
var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue;
@@ -92414,18 +94222,27 @@
// If declaration output is changed, build the project
// otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
var status_1 = projectStatus.getValue(project);
- if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
- if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) {
+ if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
+ if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status_1.type === UpToDateStatusType.OutOfDateWithPrepend)) {
projectStatus.setValue(project, {
type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: status_1.oldestOutputFileName,
+ outOfDateOutputFileName: status_1.type === UpToDateStatusType.OutOfDateWithPrepend ? status_1.outOfDateOutputFileName : status_1.oldestOutputFileName,
newerProjectName: resolved
});
}
}
else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) {
+ if (prepend) {
+ projectStatus.setValue(project, {
+ type: UpToDateStatusType.OutOfDateWithPrepend,
+ outOfDateOutputFileName: status_1.oldestOutputFileName,
+ newerProjectName: resolved
+ });
+ }
+ else {
status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
}
+ }
addProjToQueue(project);
}
}
@@ -92481,8 +94298,7 @@
}
if (options.verbose)
reportStatus(ts.Diagnostics.Building_project_0, proj);
- var resultFlags = BuildResultFlags.None;
- resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
+ var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
var configFile = parseConfigFile(proj);
if (!configFile) {
// Failed to read the config file
@@ -92498,8 +94314,7 @@
}
// TODO: handle resolve module name to cache result in project reference redirect
projectCompilerOptions = configFile.options;
- var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences);
- projectCompilerOptions = baseCompilerOptions;
+ var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, getOldProgram(proj, configFile), configFile.errors, configFile.projectReferences);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
@@ -92555,17 +94370,19 @@
var status = {
type: UpToDateStatusType.UpToDate,
newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime,
- oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile)
+ oldestOutputFileName: outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(configFile, !host.useCaseSensitiveFileNames())
};
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
}
}
@@ -92578,15 +94395,71 @@
builderPrograms.setValue(proj, program);
}
}
+ function getOldProgram(proj, parsed) {
+ if (options.force)
+ return undefined;
+ var value = builderPrograms.getValue(proj);
+ if (value)
+ return value;
+ return ts.readBuilderProgram(parsed.options, readFileWithCache);
+ }
+ function updateBundle(proj) {
+ if (options.dry) {
+ reportStatus(ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
+ return BuildResultFlags.Success;
+ }
+ if (options.verbose)
+ reportStatus(ts.Diagnostics.Updating_output_of_project_0, proj);
+ // Update js, and source map
+ var config = ts.Debug.assertDefined(parseConfigFile(proj));
+ projectCompilerOptions = config.options;
+ var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) { return parseConfigFile(resolveProjectName(ref.path)); });
+ if (ts.isString(outputFiles)) {
+ reportStatus(ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
+ return buildSingleProject(proj);
+ }
+ // Actual Emit
+ ts.Debug.assert(!!outputFiles.length);
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ var emittedOutputs = createFileMap(toPath);
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
+ emittedOutputs.setValue(name, true);
+ ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
+ });
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
+ reportAndStoreErrors(proj, emitDiagnostics);
+ projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
+ }
+ // Update timestamps for dts
+ var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
+ oldestOutputFileName: outputFiles[0].name
+ };
+ diagnostics.removeKey(proj);
+ projectStatus.setValue(proj, status);
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged;
+ }
function updateOutputTimestamps(proj) {
if (options.dry) {
- return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
+ return reportStatus(ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
}
var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
- projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
+ oldestOutputFileName: ts.getFirstProjectOutput(proj, !host.useCaseSensitiveFileNames())
+ };
+ projectStatus.setValue(proj.options.configFilePath, status);
}
function updateOutputTimestampsWorker(proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
- var outputs = getAllProjectOutputs(proj);
+ var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
if (!skipOutputs || outputs.length !== skipOutputs.getSize()) {
if (options.verbose) {
reportStatus(verboseMessage, proj.options.configFilePath);
@@ -92620,7 +94493,7 @@
reportParseConfigFileDiagnostic(proj);
continue;
}
- var outputs = getAllProjectOutputs(parsed);
+ var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) {
var output = outputs_3[_b];
if (host.fileExists(output)) {
@@ -92707,7 +94580,9 @@
// Do nothing
continue;
}
- var buildResult = buildSingleProject(next);
+ var buildResult = needsBuild(status, next) ?
+ buildSingleProject(next) : // Actual build
+ updateBundle(next); // Fake that files have been built by manipulating prepend and existing output
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
@@ -92720,6 +94595,15 @@
readFileWithCache = savedReadFileWithCache;
return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
}
+ function needsBuild(status, configFile) {
+ if (status.type !== UpToDateStatusType.OutOfDateWithPrepend || options.force)
+ return true;
+ var config = parseConfigFile(configFile);
+ return !config ||
+ config.fileNames.length === 0 ||
+ !!config.errors.length ||
+ !ts.isIncrementalCompilation(config.options);
+ }
function reportParseConfigFileDiagnostic(proj) {
reportAndStoreErrors(proj, [configFileCache.getValue(proj)]);
}
@@ -92759,33 +94643,6 @@
return ts.combinePaths(project, "tsconfig.json");
}
ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
- function getAllProjectOutputs(project) {
- if (project.options.outFile || project.options.out) {
- 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 getFirstProjectOutput(project) {
- if (project.options.outFile || project.options.out) {
- return ts.first(getOutFileOutputs(project));
- }
- for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
- var inputFile = _a[_i];
- var outputs = getOutputFileNames(inputFile, project);
- if (outputs.length) {
- return ts.first(outputs);
- }
- }
- return ts.Debug.fail("project " + project.options.configFilePath + " expected to have at least one output");
- }
function formatUpToDateStatus(configFileName, status, relName, formatMessage) {
switch (status.type) {
case UpToDateStatusType.OutOfDateWithSelf:
@@ -92800,6 +94657,8 @@
}
// Don't report anything for "up to date because it was already built" -- too verbose
break;
+ case UpToDateStatusType.OutOfDateWithPrepend:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(configFileName), relName(status.newerProjectName));
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:
@@ -92808,6 +94667,8 @@
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.TsVersionOutputOfDate:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(configFileName), status.version, ts.version);
case UpToDateStatusType.ContainerOnly:
// Don't report status on "solution" projects
case UpToDateStatusType.ComputingUpstream:
@@ -92983,6 +94844,11 @@
* typingsInstaller will run the command with `${npmLocation} install ...`.
*/
Arguments.NpmLocation = "--npmLocation";
+ /**
+ * Flag indicating that the typings installer should try to validate the default npm location.
+ * If the default npm is not found when this flag is enabled, fallback to `npm install`
+ */
+ Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
})(Arguments = server.Arguments || (server.Arguments = {}));
function hasArgument(argumentName) {
return ts.sys.args.indexOf(argumentName) >= 0;
@@ -93206,8 +95072,8 @@
if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
continue;
}
- var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- var packageJson = result_7.config;
+ 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.
@@ -93579,7 +95445,7 @@
/* @internal */
var ts;
(function (ts) {
- ts.scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true);
+ ts.scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ true);
var SemanticMeaning;
(function (SemanticMeaning) {
SemanticMeaning[SemanticMeaning["None"] = 0] = "None";
@@ -93614,7 +95480,7 @@
case 242 /* TypeAliasDeclaration */:
case 168 /* TypeLiteral */:
return 2 /* Type */;
- case 304 /* JSDocTypedefTag */:
+ case 309 /* 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 278 /* EnumMember */:
@@ -93639,14 +95505,14 @@
case 255 /* ExportDeclaration */:
return 7 /* All */;
// An external module can be a Value
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 4 /* Namespace */ | 1 /* Value */;
}
return 7 /* All */;
}
ts.getMeaningFromDeclaration = getMeaningFromDeclaration;
function getMeaningFromLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return 1 /* Value */;
}
else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) {
@@ -93852,7 +95718,7 @@
return undefined;
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
case 239 /* FunctionDeclaration */:
@@ -93870,7 +95736,7 @@
ts.getContainerNode = getContainerNode;
function getNodeKind(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */;
case 244 /* ModuleDeclaration */:
return "module" /* moduleElement */;
@@ -93879,8 +95745,8 @@
return "class" /* classElement */;
case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */;
case 242 /* TypeAliasDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return "type" /* typeElement */;
case 243 /* EnumDeclaration */: return "enum" /* enumElement */;
case 237 /* VariableDeclaration */:
@@ -94297,8 +96163,8 @@
isWhiteSpaceOnlyJsxText(child);
if (lookInPreviousChild) {
// actual start of the node is past the position - previous token should be at the end of previous child
- var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
- return candidate_2 && findRightmostToken(candidate_2, sourceFile);
+ var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
+ return candidate_1 && findRightmostToken(candidate_1, sourceFile);
}
else {
// candidate should be in this node
@@ -94306,7 +96172,7 @@
}
}
}
- ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
+ ts.Debug.assert(startNode !== undefined || n.kind === 284 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || 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.
@@ -94393,7 +96259,7 @@
}
ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute;
function isWhiteSpaceOnlyJsxText(node) {
- return ts.isJsxText(node) && node.containsOnlyWhiteSpaces;
+ return ts.isJsxText(node) && node.containsOnlyTriviaWhiteSpaces;
}
function isInTemplateString(sourceFile, position) {
var token = getTokenAtPosition(sourceFile, position);
@@ -95153,6 +97019,17 @@
return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName));
}
ts.getScriptKind = getScriptKind;
+ function getSymbolTarget(symbol) {
+ var next = symbol;
+ while (isTransientSymbol(next) && next.target) {
+ next = next.target;
+ }
+ return next;
+ }
+ ts.getSymbolTarget = getSymbolTarget;
+ function isTransientSymbol(symbol) {
+ return (symbol.flags & 33554432 /* Transient */) !== 0;
+ }
function getUniqueSymbolId(symbol, checker) {
return ts.getSymbolId(ts.skipAlias(symbol, checker));
}
@@ -95211,14 +97088,14 @@
ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext);
if (visited === node) {
// This only happens for leaf nodes - internal nodes always see their children change.
- var clone_8 = ts.getSynthesizedClone(node);
- if (ts.isStringLiteral(clone_8)) {
- clone_8.textSourceNode = node;
+ var clone_1 = ts.getSynthesizedClone(node);
+ if (ts.isStringLiteral(clone_1)) {
+ clone_1.textSourceNode = node;
}
- else if (ts.isNumericLiteral(clone_8)) {
- clone_8.numericLiteralFlags = node.numericLiteralFlags;
+ else if (ts.isNumericLiteral(clone_1)) {
+ clone_1.numericLiteralFlags = node.numericLiteralFlags;
}
- return ts.setTextRange(clone_8, node);
+ return ts.setTextRange(clone_1, node);
}
// PERF: As an optimization, rather than calling getSynthesizedClone, we'll update
// the new node created by visitEachChild with the extra changes getSynthesizedClone
@@ -95304,8 +97181,27 @@
return lastPos;
}
ts.getRenameLocation = getRenameLocation;
- function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
- ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
+ function copyLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyLeadingComments = copyLeadingComments;
+ function copyTrailingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticTrailingComment));
+ }
+ ts.copyTrailingComments = copyTrailingComments;
+ /**
+ * This function copies the trailing comments for the token that comes before `sourceNode`, as leading comments of `targetNode`.
+ * This is useful because sometimes a comment that refers to `sourceNode` will be a leading comment for `sourceNode`, according to the
+ * notion of trivia ownership, and instead will be a trailing comment for the token before `sourceNode`, e.g.:
+ * `function foo(\* not leading comment for a *\ a: string) {}`
+ * The comment refers to `a` but belongs to the `(` token, but we might want to copy it.
+ */
+ function copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyTrailingAsLeadingComments = copyTrailingAsLeadingComments;
+ function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, cb) {
+ return function (pos, end, kind, htnl) {
if (kind === 3 /* MultiLineCommentTrivia */) {
// Remove leading /*
pos += 2;
@@ -95316,10 +97212,9 @@
// Remove leading //
pos += 2;
}
- ts.addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
- });
+ cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
+ };
}
- ts.copyComments = copyComments;
function indexInTextChange(change, name) {
if (ts.startsWith(change, name))
return 0;
@@ -95400,11 +97295,35 @@
return checker.getTypeAtLocation(caseClause.parent.parent.expression);
}
ts.getSwitchedType = getSwitchedType;
+ function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
+ var checker = program.getTypeChecker();
+ var typeIsAccessible = true;
+ var notAccessible = function () { typeIsAccessible = false; };
+ var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
+ trackSymbol: function (symbol, declaration, meaning) {
+ // TODO: GH#18217
+ typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
+ },
+ reportInaccessibleThisError: notAccessible,
+ reportPrivateInBaseOfClassExpression: notAccessible,
+ reportInaccessibleUniqueSymbolError: notAccessible,
+ moduleResolverHost: {
+ readFile: host.readFile,
+ fileExists: host.fileExists,
+ directoryExists: host.directoryExists,
+ getSourceFiles: program.getSourceFiles,
+ getCurrentDirectory: program.getCurrentDirectory,
+ getCommonSourceDirectory: program.getCommonSourceDirectory,
+ }
+ });
+ return typeIsAccessible ? res : undefined;
+ }
+ ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible;
})(ts || (ts = {}));
var ts;
(function (ts) {
function createClassifier() {
- var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false);
+ var scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false);
function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) {
return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text);
}
@@ -95643,7 +97562,7 @@
var lastEnd = 0;
for (var i = 0; i < dense.length; i += 3) {
var start = dense[i];
- var length_5 = dense[i + 1];
+ var length_1 = dense[i + 1];
var type = dense[i + 2];
// Make a whitespace entry between the last item and this one.
if (lastEnd >= 0) {
@@ -95652,8 +97571,8 @@
entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace });
}
}
- entries.push({ length: length_5, classification: convertClassification(type) });
- lastEnd = start + length_5;
+ entries.push({ length: length_1, classification: convertClassification(type) });
+ lastEnd = start + length_1;
}
var whitespaceLength = text.length - lastEnd;
if (whitespaceLength > 0) {
@@ -95958,8 +97877,8 @@
var spanStart = span.start;
var spanLength = span.length;
// Make a scanner we can get trivia from.
- var triviaScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
- var mergeConflictScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
+ var triviaScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
+ var mergeConflictScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text);
var result = [];
processElement(sourceFile);
return { spans: result, endOfLineState: 0 /* None */ };
@@ -96051,18 +97970,18 @@
pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param"
pos = tag.tagName.end;
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
processJSDocParameterTag(tag);
break;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
processJSDocTemplateTag(tag);
pos = tag.end;
break;
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
@@ -96315,7 +98234,7 @@
return convertPathCompletions(completion.paths);
case 1 /* Properties */: {
var entries = [];
- Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary
+ Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 7 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries };
}
case 2 /* Types */: {
@@ -96366,6 +98285,7 @@
case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */;
case ".ts" /* Ts */: return ".ts" /* tsModifier */;
case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */;
+ case ".tsbuildinfo" /* TsBuildInfo */: return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported.");
case undefined: return "" /* none */;
default:
return ts.Debug.assertNever(extension);
@@ -96596,8 +98516,8 @@
* both foo.ts and foo.tsx become foo
*/
var foundFiles = ts.createMap(); // maps file to its extension
- for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
- var filePath = files_3[_i];
+ for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
+ var filePath = files_1[_i];
filePath = ts.normalizePath(filePath);
if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) {
continue;
@@ -96642,7 +98562,7 @@
continue;
var patterns = paths[path];
if (patterns) {
- var _loop_11 = function (name, kind, extension) {
+ var _loop_1 = function (name, kind, extension) {
// 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, extension));
@@ -96650,7 +98570,7 @@
};
for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) {
var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension;
- _loop_11(name, kind, extension);
+ _loop_1(name, kind, extension);
}
}
}
@@ -96685,7 +98605,7 @@
// (But do if we didn't find anything, e.g. 'package.json' missing.)
var foundGlobal = false;
if (fragmentDirectory === undefined) {
- var _loop_12 = function (moduleName) {
+ var _loop_2 = function (moduleName) {
if (!result.some(function (entry) { return entry.name === moduleName; })) {
foundGlobal = true;
result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined));
@@ -96693,7 +98613,7 @@
};
for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) {
var moduleName = _c[_b];
- _loop_12(moduleName);
+ _loop_2(moduleName);
}
}
if (!foundGlobal) {
@@ -96807,8 +98727,8 @@
// Check for typings specified in compiler options
var seen = ts.createMap();
var typeRoots = tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray;
- for (var _i = 0, typeRoots_2 = typeRoots; _i < typeRoots_2.length; _i++) {
- var root = typeRoots_2[_i];
+ for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
+ var root = typeRoots_1[_i];
getCompletionEntriesFromDirectories(root);
}
// Also get all @types typings installed in visible node_modules directories
@@ -96893,7 +98813,7 @@
var offset = index !== -1 ? index + 1 : 0;
// If the range is an identifier, span is unnecessary.
var length = text.length - offset;
- return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length);
+ return length === 0 || ts.isIdentifierText(text.substr(offset, length), 7 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length);
}
// Returns true if the path is explicitly relative to the script (i.e. relative to . or ..)
function isPathRelativeToScript(path) {
@@ -96978,6 +98898,7 @@
KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords";
KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords";
KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords";
+ KeywordCompletionFilters[KeywordCompletionFilters["Last"] = 6] = "Last";
})(KeywordCompletionFilters || (KeywordCompletionFilters = {}));
var GlobalsSearch;
(function (GlobalsSearch) {
@@ -97023,7 +98944,7 @@
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
}
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;
+ 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, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression;
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.
@@ -97054,7 +98975,7 @@
}
if (keywordFilters !== 0 /* None */) {
var entryNames = ts.arrayToSet(entries, function (e) { return e.name; });
- for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) {
var keywordEntry = _a[_i];
if (!entryNames.has(keywordEntry.name)) {
entries.push(keywordEntry);
@@ -97170,8 +99091,8 @@
// 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_3 = symbols; _i < symbols_3.length; _i++) {
- var symbol = symbols_3[_i];
+ for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
+ var symbol = symbols_1[_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) {
@@ -97390,7 +99311,7 @@
return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
}
function isModuleSymbol(symbol) {
- return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; });
+ return symbol.declarations.some(function (d) { return d.kind === 284 /* SourceFile */; });
}
function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) {
var typeChecker = program.getTypeChecker();
@@ -97441,11 +99362,11 @@
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
return { kind: 1 /* JsDocTagName */ };
}
- if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
currentToken = ts.getTokenAtPosition(sourceFile, position);
if (!currentToken ||
(!ts.isDeclarationName(currentToken) &&
- (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ ||
+ (currentToken.parent.kind !== 310 /* JSDocPropertyTag */ ||
currentToken.parent.name !== currentToken))) {
// Use as type location if inside tag's type expression
insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
@@ -97471,9 +99392,9 @@
// 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_3 = ts.timestamp();
+ var start_1 = ts.timestamp();
contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217
- log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_3));
+ log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1));
}
// Find the node where completion is requested on.
// Also determine whether we are trying to complete with members of that node
@@ -97498,6 +99419,14 @@
case 189 /* PropertyAccessExpression */:
propertyAccessToConvert = parent;
node = propertyAccessToConvert.expression;
+ if (node.end === contextToken.pos &&
+ ts.isCallExpression(node) &&
+ node.getChildCount(sourceFile) &&
+ ts.last(node.getChildren(sourceFile)).kind !== 21 /* CloseParenToken */) {
+ // This is likely dot from incorrectly parsed call expression and user is starting to write spread
+ // eg: Math.min(./**/)
+ return undefined;
+ }
break;
case 148 /* QualifiedName */:
node = parent.left;
@@ -97613,14 +99542,29 @@
var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker);
var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; });
var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker);
- 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 };
+ 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,
+ insideJsDocTagTypeExpression: insideJsDocTagTypeExpression
+ };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 304 /* JSDocTypedefTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 309 /* JSDocTypedefTag */:
return true;
default:
return false;
@@ -97660,7 +99604,9 @@
}
}
// 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 !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
+ if (!isTypeLocation &&
+ symbol.declarations &&
+ symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node));
}
return;
@@ -97793,8 +99739,8 @@
var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 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 !== 279 /* SourceFile */) {
- var thisType = typeChecker.tryGetThisTypeAt(scopeNode);
+ if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 284 /* SourceFile */) {
+ var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false);
if (thisType) {
for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) {
var symbol = _a[_i];
@@ -97826,7 +99772,7 @@
}
function isSnippetScope(scopeNode) {
switch (scopeNode.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 206 /* TemplateExpression */:
case 270 /* JsxExpression */:
case 218 /* Block */:
@@ -97885,6 +99831,8 @@
return parentKind === 242 /* TypeAliasDeclaration */;
case 119 /* AsKeyword */:
return parentKind === 212 /* AsExpression */;
+ case 86 /* ExtendsKeyword */:
+ return parentKind === 150 /* TypeParameter */;
}
}
return false;
@@ -98581,7 +100529,15 @@
}
return res;
});
- function getKeywordCompletions(keywordFilter) {
+ function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) {
+ if (!filterOutTsOnlyKeywords)
+ return getTypescriptKeywordCompletions(keywordFilter);
+ var index = keywordFilter + 6 /* Last */ + 1;
+ return _keywordCompletions[index] ||
+ (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter)
+ .filter(function (entry) { return !isTypeScriptOnlyKeyword(ts.stringToToken(entry.name)); }));
+ }
+ function getTypescriptKeywordCompletions(keywordFilter) {
return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) {
var kind = ts.stringToToken(entry.name);
switch (keywordFilter) {
@@ -98605,6 +100561,39 @@
}
}));
}
+ function isTypeScriptOnlyKeyword(kind) {
+ switch (kind) {
+ case 118 /* AbstractKeyword */:
+ case 120 /* AnyKeyword */:
+ case 146 /* BigIntKeyword */:
+ case 123 /* BooleanKeyword */:
+ case 125 /* DeclareKeyword */:
+ case 84 /* EnumKeyword */:
+ case 145 /* GlobalKeyword */:
+ case 109 /* ImplementsKeyword */:
+ case 127 /* InferKeyword */:
+ case 110 /* InterfaceKeyword */:
+ case 128 /* IsKeyword */:
+ case 129 /* KeyOfKeyword */:
+ case 130 /* ModuleKeyword */:
+ case 131 /* NamespaceKeyword */:
+ case 132 /* NeverKeyword */:
+ case 135 /* NumberKeyword */:
+ case 136 /* ObjectKeyword */:
+ case 113 /* PrivateKeyword */:
+ case 114 /* ProtectedKeyword */:
+ case 115 /* PublicKeyword */:
+ case 133 /* ReadonlyKeyword */:
+ case 138 /* StringKeyword */:
+ case 139 /* SymbolKeyword */:
+ case 140 /* TypeKeyword */:
+ case 142 /* UniqueKeyword */:
+ case 143 /* UnknownKeyword */:
+ return true;
+ default:
+ return false;
+ }
+ }
function isInterfaceOrTypeLiteralCompletionKeyword(kind) {
return kind === 133 /* ReadonlyKeyword */;
}
@@ -98658,7 +100647,7 @@
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 306 /* SyntaxList */:
+ case 311 /* 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);
@@ -98843,7 +100832,7 @@
var child = throwStatement;
while (child.parent) {
var parent = child.parent;
- if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) {
+ if (ts.isFunctionBlock(parent) || parent.kind === 284 /* SourceFile */) {
return parent;
}
// A throw-statement is only owned by a try-statement if the try-statement has
@@ -98901,7 +100890,7 @@
var container = declaration.parent;
switch (container.kind) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 271 /* CaseClause */:
case 272 /* DefaultClause */:
@@ -99399,7 +101388,7 @@
}
else if (!isAvailableThroughGlobal) {
var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
- ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
+ ts.Debug.assert(sourceFileLike.kind === 284 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
addIndirectUsers(sourceFileLike);
}
@@ -99508,7 +101497,7 @@
}
}
/**
- * `import x = require("./x") or `import * as x from "./x"`.
+ * `import x = require("./x")` or `import * as x from "./x"`.
* An `export =` may be imported by this syntax, so it may be a direct import.
* If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here.
*/
@@ -99565,10 +101554,10 @@
function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
var refs = [];
var checker = program.getTypeChecker();
- for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
- var referencingFile = sourceFiles_3[_i];
+ for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
+ var referencingFile = sourceFiles_1[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
- if (searchSourceFile.kind === 279 /* SourceFile */) {
+ if (searchSourceFile.kind === 284 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
var ref = _b[_a];
if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
@@ -99596,8 +101585,8 @@
/** 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_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
- var sourceFile = sourceFiles_4[_i];
+ for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
+ var sourceFile = sourceFiles_2[_i];
if (cancellationToken)
cancellationToken.throwIfCancellationRequested();
forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
@@ -99616,7 +101605,7 @@
}
/** 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 === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
+ return ts.forEach(sourceFileLike.kind === 284 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action));
});
}
@@ -99840,7 +101829,7 @@
return node.getSourceFile();
}
var parent = node.parent;
- if (parent.kind === 279 /* SourceFile */) {
+ if (parent.kind === 284 /* SourceFile */) {
return parent;
}
ts.Debug.assert(parent.kind === 245 /* ModuleBlock */);
@@ -99902,16 +101891,16 @@
}
FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition;
function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* 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 === 276 /* ShorthandPropertyAssignment */) {
- var result_8 = [];
- FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_8.push(nodeEntry(node)); });
- return result_8;
+ var result_1 = [];
+ FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); });
+ return result_1;
}
else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
@@ -99943,27 +101932,27 @@
case 0 /* Symbol */: {
var symbol = def.symbol;
var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
- var name_4 = 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_4, kind: kind_1, displayParts: displayParts_1 };
+ 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 };
}
case 1 /* Label */: {
- 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)] };
+ 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)] };
}
case 2 /* Keyword */: {
- var node_4 = def.node;
- var name_5 = ts.tokenToString(node_4.kind);
- return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] };
+ 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 */ }] };
}
case 3 /* This */: {
- 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 };
+ 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 };
}
case 4 /* String */: {
- 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)] };
+ 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)] };
}
default:
return ts.Debug.assertNever(def);
@@ -100122,8 +102111,8 @@
case 248 /* ImportEqualsDeclaration */:
case 253 /* ImportSpecifier */:
case 241 /* InterfaceDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
case 267 /* JsxAttribute */:
case 244 /* ModuleDeclaration */:
case 247 /* NamespaceExportDeclaration */:
@@ -100148,8 +102137,8 @@
return !!decl.initializer || ts.isCatchClause(decl.parent);
case 155 /* MethodSignature */:
case 153 /* PropertySignature */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
return false;
default:
return ts.Debug.failBadSyntaxKind(decl);
@@ -100241,7 +102230,7 @@
result = references;
continue;
}
- var _loop_13 = function (entry) {
+ var _loop_3 = function (entry) {
if (!entry.definition || entry.definition.type !== 0 /* Symbol */) {
result.push(entry);
return "continue";
@@ -100273,7 +102262,7 @@
};
for (var _b = 0, references_1 = references; _b < references_1.length; _b++) {
var entry = references_1[_b];
- _loop_13(entry);
+ _loop_3(entry);
}
}
return result;
@@ -100309,7 +102298,7 @@
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
switch (decl.kind) {
- case 279 /* SourceFile */:
+ case 284 /* 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 244 /* ModuleDeclaration */:
@@ -100382,11 +102371,16 @@
}
else {
var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] });
+ getReferencesInContainerOrFiles(symbol, state, search);
+ }
+ return result;
+ }
+ function getReferencesInContainerOrFiles(symbol, state, search) {
// Try to get the smallest valid scope that we can limit our search to;
// otherwise we'll need to search globally (i.e. include each file).
var scope = getSymbolScope(symbol);
if (scope) {
- getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope)));
+ getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(state.sourceFiles, scope)));
}
else {
// Global search
@@ -100397,8 +102391,6 @@
}
}
}
- return result;
- }
function getSpecialSearchKind(node) {
switch (node.kind) {
case 124 /* ConstructorKeyword */:
@@ -100450,9 +102442,7 @@
* Unlike `Search`, there is only one `State`.
*/
var State = /** @class */ (function () {
- function State(sourceFiles, sourceFilesSet,
- /** True if we're searching for constructor references. */
- specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
+ function State(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) {
this.sourceFiles = sourceFiles;
this.sourceFilesSet = sourceFilesSet;
this.specialSearchKind = specialSearchKind;
@@ -100533,8 +102523,8 @@
var sourceId = ts.getNodeId(sourceFile);
var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap());
var anyNewSymbols = false;
- for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) {
- var sym = symbols_4[_i];
+ for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
+ var sym = symbols_2[_i];
anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols;
}
return anyNewSymbols;
@@ -100673,14 +102663,14 @@
return undefined;
}
var scope;
- for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) {
- var declaration = declarations_11[_i];
+ for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
+ var declaration = declarations_1[_i];
var container = ts.getContainerNode(declaration);
if (scope && scope !== container) {
// Different declarations have different containers, bail out
return undefined;
}
- if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
+ if (!container || container.kind === 284 /* 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;
@@ -100725,8 +102715,8 @@
if (!signature.name || !ts.isIdentifier(signature.name))
return;
var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name));
- for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
- var sourceFile = sourceFiles_5[_i];
+ for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
+ var sourceFile = sourceFiles_3[_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)
@@ -100767,8 +102757,8 @@
// We found a match. Make sure it's not part of a larger word (i.e. the char
// before and after it have to be a non-identifier char).
var endPosition = position + symbolNameLength;
- if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 6 /* Latest */)) &&
- (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 6 /* Latest */))) {
+ if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 7 /* Latest */)) &&
+ (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 7 /* Latest */))) {
// Found a real match. Keep searching.
positions.push(position);
}
@@ -100917,7 +102907,9 @@
}
// For `export { foo as bar }`, rename `foo`, but not `bar`.
if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) {
- var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */;
+ var isDefaultExport = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */
+ || exportSpecifier.name.originalKeywordKind === 80 /* DefaultKeyword */;
+ var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */;
var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol);
var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker));
searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
@@ -101004,6 +102996,7 @@
var classExtending = tryGetClassByExtendingIdentifier(referenceLocation);
if (classExtending) {
findSuperConstructorAccesses(classExtending, pusher());
+ findInheritedConstructorReferences(classExtending, state);
}
}
}
@@ -101036,12 +103029,16 @@
* Reference the constructor and all calls to `new this()`.
*/
function findOwnConstructorReferences(classSymbol, sourceFile, addNode) {
- for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) {
+ var constructorSymbol = getClassConstructorSymbol(classSymbol);
+ if (constructorSymbol) {
+ for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile);
ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword);
addNode(ctrKeyword);
}
+ }
+ if (classSymbol.exports) {
classSymbol.exports.forEach(function (member) {
var decl = member.valueDeclaration;
if (decl && decl.kind === 156 /* MethodDeclaration */) {
@@ -101056,13 +103053,17 @@
}
});
}
+ }
+ function getClassConstructorSymbol(classSymbol) {
+ return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */);
+ }
/** Find references to `super` in the constructor of an extending class. */
- function findSuperConstructorAccesses(cls, addNode) {
- var ctr = cls.symbol.members.get("__constructor" /* Constructor */);
- if (!ctr) {
+ function findSuperConstructorAccesses(classDeclaration, addNode) {
+ var constructor = getClassConstructorSymbol(classDeclaration.symbol);
+ if (!constructor) {
return;
}
- for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) {
+ for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
ts.Debug.assert(decl.kind === 157 /* Constructor */);
var body = decl.body;
@@ -101075,6 +103076,16 @@
}
}
}
+ function hasOwnConstructor(classDeclaration) {
+ return !!getClassConstructorSymbol(classDeclaration.symbol);
+ }
+ function findInheritedConstructorReferences(classDeclaration, state) {
+ if (hasOwnConstructor(classDeclaration))
+ return;
+ var classSymbol = classDeclaration.symbol;
+ var search = state.createSearch(/*location*/ undefined, classSymbol, /*comingFrom*/ undefined);
+ getReferencesInContainerOrFiles(classSymbol, state, search);
+ }
function addImplementationReferences(refNode, addReference, state) {
// Check if we found a function/propertyAssignment/method with an implementation or initializer
if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) {
@@ -101239,7 +103250,7 @@
staticFlag &= ts.getModifierFlags(searchSpaceNode);
searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) {
return undefined;
}
@@ -101252,7 +103263,7 @@
default:
return undefined;
}
- var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
+ var references = ts.flatMap(searchSpaceNode.kind === 284 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) {
if (!ts.isThis(node)) {
@@ -101271,8 +103282,8 @@
// 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 279 /* SourceFile */:
- return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
+ case 284 /* SourceFile */:
+ return container.kind === 284 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
}
});
}).map(function (n) { return FindAllReferences.nodeEntry(n); });
@@ -101428,8 +103439,8 @@
// To achieve that we will keep iterating until the result stabilizes.
// Remember the last meaning
lastIterationMeaning = meaning;
- for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) {
- var declaration = declarations_12[_i];
+ for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
+ var declaration = declarations_2[_i];
var declarationMeaning = ts.getMeaningFromDeclaration(declaration);
if (declarationMeaning & meaning) {
meaning |= declarationMeaning;
@@ -101578,8 +103589,8 @@
// 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_5 = elements; _i < elements_5.length; _i++) {
- var element = elements_5[_i];
+ for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
+ var element = elements_1[_i];
foundExactMatch = tryUpdateString(element) || foundExactMatch;
}
return foundExactMatch;
@@ -101601,7 +103612,7 @@
}
function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) {
var allFiles = program.getSourceFiles();
- var _loop_14 = function (sourceFile) {
+ var _loop_4 = function (sourceFile) {
var newFromOld = oldToNew(sourceFile.path);
var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path;
var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath);
@@ -101633,7 +103644,7 @@
};
for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) {
var sourceFile = allFiles_1[_i];
- _loop_14(sourceFile);
+ _loop_4(sourceFile);
}
}
function combineNormal(pathA, pathB) {
@@ -101663,9 +103674,9 @@
return undefined;
// First try resolved module
if (resolved.resolvedModule) {
- var result_9 = tryChange(resolved.resolvedModule.resolvedFileName);
- if (result_9)
- return result_9;
+ var result_2 = tryChange(resolved.resolvedModule.resolvedFileName);
+ if (result_2)
+ return result_2;
}
// Then failed lookups except package.json since we dont want to touch them (only included ts/js files)
var result = ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson);
@@ -101775,10 +103786,10 @@
// bar<Test>(({pr/*goto*/op1})=>{});
if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) &&
(node === (parent.propertyName || parent.name))) {
- var name_6 = ts.getNameFromPropertyName(node);
+ var name_3 = ts.getNameFromPropertyName(node);
var type = typeChecker.getTypeAtLocation(parent.parent);
- return name_6 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) {
- var prop = t.getProperty(name_6);
+ 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);
});
}
@@ -102126,11 +104137,11 @@
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return [declaration];
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return [declaration, declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
@@ -102151,16 +104162,16 @@
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
var name = tag.name;
return name ? withNode(name) : comment;
default:
@@ -102371,7 +104382,7 @@
: undefined;
return { commentOwner: commentOwner, parameters: parameters_1 };
}
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return "quit";
case 244 /* ModuleDeclaration */:
// If in walking up the tree, we hit a a nested namespace declaration,
@@ -102423,7 +104434,7 @@
if (!patternMatcher)
return ts.emptyArray;
var rawItems = [];
- var _loop_15 = function (sourceFile) {
+ var _loop_5 = function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
if (excludeDtsFiles && sourceFile.isDeclarationFile) {
return "continue";
@@ -102433,9 +104444,9 @@
});
};
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
- for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
- var sourceFile = sourceFiles_6[_i];
- _loop_15(sourceFile);
+ for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
+ var sourceFile = sourceFiles_4[_i];
+ _loop_5(sourceFile);
}
rawItems.sort(compareNavigateToItems);
return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem);
@@ -102448,8 +104459,8 @@
if (!match) {
return; // continue to next named declarations
}
- for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) {
- var declaration = declarations_13[_i];
+ for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
+ var declaration = declarations_3[_i];
if (!shouldKeepItem(declaration, checker))
continue;
if (patternMatcher.patternContainsDots) {
@@ -102931,7 +104942,7 @@
}
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
var sourceFile = node;
return ts.isExternalModule(sourceFile)
? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\""
@@ -102983,10 +104994,10 @@
case 243 /* EnumDeclaration */:
case 241 /* InterfaceDeclaration */:
case 244 /* ModuleDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 242 /* TypeAliasDeclaration */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return true;
case 157 /* Constructor */:
case 156 /* MethodDeclaration */:
@@ -103007,7 +105018,7 @@
}
switch (navigationBarNodeKind(item.parent)) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
return true;
@@ -103092,7 +105103,7 @@
return !member.name || member.name.kind === 149 /* ComputedPropertyName */;
}
function getNodeSpan(node) {
- return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
+ return node.kind === 284 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
}
function getModifiers(node) {
if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) {
@@ -103213,8 +105224,8 @@
else {
// Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: false,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include,
suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
});
}
@@ -103228,7 +105239,7 @@
function removeUnusedImports(oldImports, sourceFile, program) {
var typeChecker = program.getTypeChecker();
var jsxNamespace = typeChecker.getJsxNamespace(sourceFile);
- var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */);
+ var jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */);
var usedImports = [];
for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) {
var importDecl = oldImports_1[_i];
@@ -103552,8 +105563,8 @@
var lastSingleLineCommentEnd = -1;
var singleLineCommentCount = 0;
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;
+ 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;
cancellationToken.throwIfCancellationRequested();
switch (kind) {
case 2 /* SingleLineCommentTrivia */:
@@ -103939,7 +105950,7 @@
if (ch >= 65 /* A */ && ch <= 90 /* Z */) {
return true;
}
- if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) {
+ if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 7 /* Latest */)) {
return false;
}
// TODO: find a way to determine this for any unicode characters in a
@@ -103952,7 +105963,7 @@
if (ch >= 97 /* a */ && ch <= 122 /* z */) {
return true;
}
- if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) {
+ if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 7 /* Latest */)) {
return false;
}
// TODO: find a way to determine this for any unicode characters in a
@@ -103963,15 +105974,15 @@
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(str, value) {
var n = str.length - value.length;
- var _loop_16 = function (start) {
+ var _loop_6 = 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_1 = _loop_6(start);
+ if (typeof state_1 === "object")
+ return state_1.value;
}
return -1;
}
@@ -104982,7 +106993,7 @@
return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
}
function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) {
- var _loop_17 = function (n) {
+ var _loop_7 = 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); });
@@ -104992,9 +107003,9 @@
}
};
for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) {
- var state_5 = _loop_17(n);
- if (typeof state_5 === "object")
- return state_5.value;
+ var state_2 = _loop_7(n);
+ if (typeof state_2 === "object")
+ return state_2.value;
}
return undefined;
}
@@ -105069,13 +107080,13 @@
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); })));
+ var params = ts.createNodeArray(thisParameter.concat(checker.getExpandedParameters(candidateSignature).map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); })));
printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer);
});
return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) };
}
function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) {
- var isVariadic = candidateSignature.hasRestParameter;
+ var isVariadic = checker.hasEffectiveRestParameter(candidateSignature);
var printer = ts.createPrinter({ removeComments: true });
var typeParameterParts = ts.mapToDisplayParts(function (writer) {
if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) {
@@ -105083,7 +107094,7 @@
printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer);
}
});
- var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); });
+ var parameters = checker.getExpandedParameters(candidateSignature).map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); });
return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] };
}
function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) {
@@ -105272,8 +107283,8 @@
var name = importNameForConvertToDefaultImport(importNode);
if (!name)
continue;
- var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
- var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName);
+ var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
+ var resolvedFile = module && program.getSourceFile(module.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));
}
@@ -105288,8 +107299,8 @@
case 196 /* FunctionExpression */:
var decl = ts.getDeclarationOfExpando(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;
}
@@ -105726,7 +107737,7 @@
displayParts.push(ts.spacePart());
addFullSymbolName(symbol);
}
- if (symbolFlags & 1536 /* Module */) {
+ if (symbolFlags & 1536 /* Module */ && !isThisExpression) {
prefixNextMeaning();
var declaration = ts.getDeclarationOfKind(symbol, 244 /* ModuleDeclaration */);
var isNamespace = declaration && declaration.name && declaration.name.kind === 72 /* Identifier */;
@@ -105910,7 +107921,7 @@
// 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 === 279 /* SourceFile */; })) {
+ if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 284 /* SourceFile */; })) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) {
@@ -106035,7 +108046,7 @@
// 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 === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
+ if (parent.kind === 284 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
return false;
}
}
@@ -106149,7 +108160,7 @@
return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
});
options = ts.cloneCompilerOptions(options);
- var _loop_18 = function (opt) {
+ var _loop_8 = function (opt) {
if (!ts.hasProperty(options, opt.name)) {
return "continue";
}
@@ -106168,7 +108179,7 @@
};
for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
var opt = commandLineOptionsStringToEnum_1[_i];
- _loop_18(opt);
+ _loop_8(opt);
}
return options;
}
@@ -106264,8 +108275,8 @@
(function (ts) {
var formatting;
(function (formatting) {
- var standardScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
- var jsxScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */);
+ var standardScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
+ var jsxScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */);
var ScanAction;
(function (ScanAction) {
ScanAction[ScanAction["Scan"] = 0] = "Scan";
@@ -106859,7 +108870,7 @@
case 226 /* ForInStatement */:
// "in" keyword in [P in keyof T]: T[P]
case 150 /* TypeParameter */:
- return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */;
+ return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */ || context.currentTokenSpan.kind === 59 /* EqualsToken */ || context.nextTokenSpan.kind === 59 /* EqualsToken */;
// Technically, "of" is not a binary operator, but format it the same way as "in"
case 227 /* ForOfStatement */:
return context.currentTokenSpan.kind === 147 /* OfKeyword */ || context.nextTokenSpan.kind === 147 /* OfKeyword */;
@@ -107360,7 +109371,7 @@
case 244 /* ModuleDeclaration */:
var body = parent.body;
return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 245 /* ModuleBlock */:
return ts.rangeContainsRange(parent.statements, node);
@@ -108479,7 +110490,7 @@
// - 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 === 279 /* SourceFile */ || !parentAndChildShareLine);
+ (parent.kind === 284 /* SourceFile */ || !parentAndChildShareLine);
if (!useActualIndentation) {
return -1 /* Unknown */;
}
@@ -108567,7 +110578,7 @@
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return getList(node.typeParameters);
case 192 /* NewExpression */:
case 191 /* CallExpression */:
@@ -108816,11 +110827,23 @@
ts.Debug.assert(typeof end === "number");
n.__end = end;
}
- var Position;
- (function (Position) {
- Position[Position["FullStart"] = 0] = "FullStart";
- Position[Position["Start"] = 1] = "Start";
- })(Position = textChanges_3.Position || (textChanges_3.Position = {}));
+ var LeadingTriviaOption;
+ (function (LeadingTriviaOption) {
+ /** Exclude all leading trivia (use getStart()) */
+ LeadingTriviaOption[LeadingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include leading trivia and,
+ * if there are no line breaks between the node and the previous token,
+ * include all trivia between the node and the previous token
+ */
+ LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll";
+ })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {}));
+ var TrailingTriviaOption;
+ (function (TrailingTriviaOption) {
+ /** Exclude all trailing trivia (use getEnd()) */
+ TrailingTriviaOption[TrailingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include trailing trivia */
+ TrailingTriviaOption[TrailingTriviaOption["Include"] = 1] = "Include";
+ })(TrailingTriviaOption = textChanges_3.TrailingTriviaOption || (textChanges_3.TrailingTriviaOption = {}));
function skipWhitespacesAndLineBreaks(text, start) {
return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
@@ -108836,9 +110859,9 @@
}
return false;
}
- textChanges_3.useNonAdjustedPositions = {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: true,
+ var useNonAdjustedPositions = {
+ leadingTriviaOption: LeadingTriviaOption.Exclude,
+ trailingTriviaOption: TrailingTriviaOption.Exclude,
};
var ChangeKind;
(function (ChangeKind) {
@@ -108848,10 +110871,11 @@
ChangeKind[ChangeKind["Text"] = 3] = "Text";
})(ChangeKind || (ChangeKind = {}));
function getAdjustedRange(sourceFile, startNode, endNode, options) {
- return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) };
+ return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) };
}
- function getAdjustedStartPosition(sourceFile, node, options, position) {
- if (options.useNonAdjustedStartPosition) {
+ function getAdjustedStartPosition(sourceFile, node, options) {
+ var leadingTriviaOption = options.leadingTriviaOption;
+ if (leadingTriviaOption === LeadingTriviaOption.Exclude) {
return node.getStart(sourceFile);
}
var fullStart = node.getFullStart();
@@ -108869,7 +110893,7 @@
// fullstart
// when b is replaced - we usually want to keep the leading trvia
// when b is deleted - we delete it
- return position === Position.Start ? start : fullStart;
+ return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start;
}
// get start position of the line following the line that contains fullstart position
// (but only if the fullstart isn't the very beginning of the file)
@@ -108881,11 +110905,12 @@
}
function getAdjustedEndPosition(sourceFile, node, options) {
var end = node.end;
- if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
+ var trailingTriviaOption = options.trailingTriviaOption;
+ if (trailingTriviaOption === TrailingTriviaOption.Exclude || (ts.isExpression(node) && trailingTriviaOption !== TrailingTriviaOption.Include)) {
return end;
}
var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
- return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
+ return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)))
? newEnd
: end;
}
@@ -108930,15 +110955,15 @@
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 = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
- var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
+ var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
@@ -108946,11 +110971,11 @@
this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
};
ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
};
ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options);
};
ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
@@ -108958,14 +110983,14 @@
this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
};
ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
};
ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
- this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text);
+ this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text);
};
ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
@@ -108993,7 +111018,7 @@
};
ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) {
if (blankLineBetween === void 0) { blankLineBetween = false; }
- this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
+ this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
};
ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) {
var pos = before.getStart(sourceFile);
@@ -109100,7 +111125,7 @@
this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true));
};
ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) {
- var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start);
+ var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {});
this.insertNodeAt(sourceFile, pos, newNode, {
prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
suffix: this.newLineCharacter
@@ -109340,7 +111365,7 @@
ChangeTracker.prototype.finishDeleteDeclarations = function () {
var _this = this;
var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
- var _loop_19 = function (sourceFile, node) {
+ var _loop_9 = 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));
@@ -109353,7 +111378,7 @@
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_19(sourceFile, node);
+ _loop_9(sourceFile, node);
}
deletedNodesInLists.forEach(function (node) {
var sourceFile = node.getSourceFile();
@@ -109390,7 +111415,7 @@
textChanges_3.ChangeTracker = ChangeTracker;
// find first non-whitespace position in the leading trivia of the node
function startPositionToDeleteNodeInList(sourceFile, node) {
- return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
function getClassOrObjectBraceEnds(cls, sourceFile) {
return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end];
@@ -109410,14 +111435,14 @@
// 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_20 = function (i) {
+ var _loop_10 = 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_20(i);
+ _loop_10(i);
}
var textChanges = normalized.map(function (c) {
return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
@@ -109434,7 +111459,7 @@
function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) {
// TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this
var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter);
- var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind);
+ var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 7 /* ESNext */, /*setParentNodes*/ true, scriptKind);
var changes = ts.formatting.formatDocument(sourceFile, formatContext);
return applyChanges(nonFormattedText, changes) + newLineCharacter;
}
@@ -109727,7 +111752,7 @@
case 249 /* ImportDeclaration */:
deleteNode(changes, sourceFile, node,
// For first import, leave header comment in place
- node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined);
+ node === sourceFile.imports[0].parent ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined);
break;
case 186 /* BindingElement */:
var pattern = node.parent;
@@ -109765,7 +111790,7 @@
deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
}
else {
- deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined);
+ deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { trailingTriviaOption: TrailingTriviaOption.Exclude } : undefined);
}
}
}
@@ -109836,8 +111861,8 @@
/** 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);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, node, options);
var endPosition = getAdjustedEndPosition(sourceFile, node, options);
changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
}
@@ -110024,6 +112049,40 @@
(function (ts) {
var codefix;
(function (codefix) {
+ var fixId = "addNameToNamelessParameter";
+ var errorCodes = [ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_parameter_name, fixId, ts.Diagnostics.Add_names_to_all_parameters_without_names)];
+ },
+ fixIds: [fixId],
+ 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);
+ if (!ts.isIdentifier(token)) {
+ return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.formatSyntaxKind(token.kind));
+ }
+ var param = token.parent;
+ if (!ts.isParameter(param)) {
+ return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.formatSyntaxKind(token.kind));
+ }
+ var i = param.parent.parameters.indexOf(param);
+ ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one.");
+ ts.Debug.assert(i > -1, "Parameter not found in parent parameter list.");
+ var replacement = ts.createParameter(
+ /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer);
+ changeTracker.replaceNode(sourceFile, token, replacement);
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
var fixId = "annotateWithTypeFromJSDoc";
var errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code];
codefix.registerCodeFix({
@@ -110096,18 +112155,18 @@
}
function transformJSDocType(node) {
switch (node.kind) {
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 164 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -110131,7 +112190,7 @@
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
+ var isRest = node.type.kind === 295 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
var name = node.name || (isRest ? "rest" : "arg" + index);
var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken;
return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
@@ -110287,7 +112346,7 @@
}
if (ts.isPropertyAccessExpression(parent)) {
var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken);
- var typeNode = getTypeNodeIfAccessible(type, parent, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host);
if (typeNode) {
// Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags
var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ "");
@@ -110391,7 +112450,7 @@
}
}
function annotate(changes, sourceFile, declaration, type, program, host) {
- var typeNode = getTypeNodeIfAccessible(type, declaration, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host);
if (typeNode) {
if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) {
var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration;
@@ -110417,7 +112476,7 @@
// only infer parameters that have (1) no type and (2) an accessible inferred type
if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name))
return;
- var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host);
+ var typeNode = inference.type && ts.getTypeNodeIfAccessible(inference.type, param, program, host);
var name = ts.getSynthesizedClone(param.name);
ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), "");
@@ -110434,47 +112493,33 @@
return !!merged;
}); });
var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray((oldTags || ts.emptyArray).concat(unmergedNewTags)));
- changes.insertJsdocCommentBefore(sourceFile, parent, tag);
+ var jsDocNode = parent.kind === 197 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent;
+ jsDocNode.jsDoc = parent.jsDoc;
+ jsDocNode.jsDocCache = parent.jsDocCache;
+ changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag);
+ }
+ function getJsDocNodeForArrowFunction(signature) {
+ if (signature.parent.kind === 154 /* PropertyDeclaration */) {
+ return signature.parent;
+ }
+ return signature.parent.parent;
}
function tryMergeJsdocTags(oldTag, newTag) {
if (oldTag.kind !== newTag.kind) {
return undefined;
}
switch (oldTag.kind) {
- case 299 /* JSDocParameterTag */: {
+ case 304 /* JSDocParameterTag */: {
var oldParam = oldTag;
var newParam = newTag;
return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText
? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment)
: undefined;
}
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment);
}
}
- function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
- var checker = program.getTypeChecker();
- var typeIsAccessible = true;
- var notAccessible = function () { typeIsAccessible = false; };
- var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
- trackSymbol: function (symbol, declaration, meaning) {
- // TODO: GH#18217
- typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
- },
- reportInaccessibleThisError: notAccessible,
- reportPrivateInBaseOfClassExpression: notAccessible,
- reportInaccessibleUniqueSymbolError: notAccessible,
- moduleResolverHost: {
- readFile: host.readFile,
- fileExists: host.fileExists,
- directoryExists: host.directoryExists,
- getSourceFiles: program.getSourceFiles,
- getCurrentDirectory: program.getCurrentDirectory,
- getCommonSourceDirectory: program.getCommonSourceDirectory,
- }
- });
- return typeIsAccessible ? res : undefined;
- }
function getReferences(token, program, cancellationToken) {
// Position shouldn't matter since token is not a SourceFile.
return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) {
@@ -110773,8 +112818,8 @@
}
function removeLowPriorityInferences(inferences, priorities) {
var toRemove = [];
- for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
- var i = inferences_2[_i];
+ for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
+ var i = inferences_1[_i];
for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) {
var _b = priorities_1[_a], high = _b.high, low = _b.low;
if (high(i)) {
@@ -110866,8 +112911,8 @@
types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); }));
if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) {
var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217
- var types_19 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); });
- types_19.push(checker.createPromiseType(types_19.length ? checker.getUnionType(types_19, 2 /* Subtype */) : checker.getAnyType()));
+ var types_1 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); });
+ types_1.push(checker.createPromiseType(types_1.length ? checker.getUnionType(types_1, 2 /* Subtype */) : checker.getAnyType()));
}
else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) {
types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)));
@@ -110876,7 +112921,7 @@
types.push(checker.createArrayType(recur(usageContext.numberIndexContext)));
}
else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) {
- var members_6 = ts.createUnderscoreEscapedMap();
+ var members_1 = ts.createUnderscoreEscapedMap();
var callSignatures = [];
var constructSignatures = [];
var stringIndexInfo = void 0;
@@ -110884,7 +112929,7 @@
usageContext.properties.forEach(function (context, name) {
var symbol = checker.createSymbol(4 /* Property */, name);
symbol.type = recur(context);
- members_6.set(name, symbol);
+ members_1.set(name, symbol);
});
}
if (usageContext.callContexts) {
@@ -110902,7 +112947,7 @@
if (usageContext.stringIndexContext) {
stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false);
}
- types.push(checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217
+ types.push(checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217
}
return types;
function recur(innerContext) {
@@ -110987,7 +113032,7 @@
precedingNode = ctorDeclaration.parent.parent;
newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
if (ctorDeclaration.parent.declarations.length === 1) {
- ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
+ ts.copyLeadingComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
changes.delete(sourceFile, precedingNode);
}
else {
@@ -110998,7 +113043,7 @@
if (!newClassDeclaration) {
return undefined;
}
- ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile);
+ ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile);
// Because the preceding node could be touched, we need to insert nodes before delete nodes.
changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
function createClassElementsFromSymbol(symbol) {
@@ -111051,7 +113096,7 @@
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
case 197 /* ArrowFunction */: {
@@ -111069,7 +113114,7 @@
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
default: {
@@ -111079,7 +113124,7 @@
}
var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
/*type*/ undefined, assignmentBinaryExpression.right);
- ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
return prop;
}
}
@@ -111171,7 +113216,7 @@
var newNodes = transformExpression(node, transformer, node);
changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes);
}
- var _loop_21 = function (statement) {
+ var _loop_11 = function (statement) {
ts.forEachChild(statement, function visit(node) {
if (ts.isCallExpression(node)) {
startTransformation(node, statement);
@@ -111183,7 +113228,7 @@
};
for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) {
var statement = returnStatements_1[_i];
- _loop_21(statement);
+ _loop_11(statement);
}
}
function getReturnStatementsWithPromiseHandlers(body) {
@@ -111508,8 +113553,8 @@
if (innerCbBody.length > 0) {
return innerCbBody;
}
- var type_6 = transformer.checker.getTypeAtLocation(func);
- var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType();
+ var type_1 = transformer.checker.getTypeAtLocation(func);
+ var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType();
var rightHandSide = ts.getSynthesizedDeepClone(funcBody);
var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide;
if (!shouldReturn) {
@@ -112835,7 +114880,7 @@
});
typeDeclToMembers.forEach(function (infos, classDeclaration) {
var supers = getAllSupers(classDeclaration, checker);
- var _loop_22 = function (info) {
+ var _loop_12 = function (info) {
// If some superclass added this property, don't add it again.
if (supers.some(function (superClassOrInterface) {
var superInfos = typeDeclToMembers.get(superClassOrInterface);
@@ -112862,7 +114907,7 @@
};
for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
var info = infos_1[_i];
- _loop_22(info);
+ _loop_12(info);
}
});
}));
@@ -113040,6 +115085,40 @@
(function (ts) {
var codefix;
(function (codefix) {
+ var fixId = "addMissingNewOperator";
+ var errorCodes = [ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile, span = context.span;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingNewOperator(t, sourceFile, span); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_new_operator_to_call, fixId, ts.Diagnostics.Add_missing_new_operator_to_all_calls)];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ return addMissingNewOperator(changes, context.sourceFile, diag);
+ }); },
+ });
+ function addMissingNewOperator(changes, sourceFile, span) {
+ var call = ts.cast(findAncestorMatchingSpan(sourceFile, span), ts.isCallExpression);
+ var newExpression = ts.createNew(call.expression, call.typeArguments, call.arguments);
+ changes.replaceNode(sourceFile, call, newExpression);
+ }
+ function findAncestorMatchingSpan(sourceFile, span) {
+ var token = ts.getTokenAtPosition(sourceFile, span.start);
+ var end = ts.textSpanEnd(span);
+ while (token.end < end) {
+ token = token.parent;
+ }
+ return token;
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
var fixName = "fixCannotFindModule";
var fixIdInstallTypesPackage = "installTypesPackage";
var fixIdGenerateTypes = "generateTypes";
@@ -113325,6 +115404,32 @@
(function (ts) {
var codefix;
(function (codefix) {
+ var fixId = "enableExperimentalDecorators";
+ var errorCodes = [
+ 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.code
+ ];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var configFile = context.program.getCompilerOptions().configFile;
+ if (configFile === undefined) {
+ return undefined;
+ }
+ var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) { return makeChange(changeTracker, configFile); });
+ return [codefix.createCodeFixActionNoFixId(fixId, changes, ts.Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)];
+ },
+ fixIds: [fixId],
+ });
+ function makeChange(changeTracker, configFile) {
+ codefix.setJsonCompilerOptionValue(changeTracker, configFile, "experimentalDecorators", ts.createTrue());
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
var fixId = "extendsInterfaceBecomesImplements";
var errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code];
codefix.registerCodeFix({
@@ -113768,7 +115873,7 @@
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 === 286 /* JSDocNullableType */) {
+ if (typeNode.kind === 291 /* 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, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -113788,7 +115893,7 @@
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 291 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -114037,8 +116142,8 @@
outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences));
break;
}
- for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
- var signature = signatures_7[_i];
+ for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
+ var signature = signatures_1[_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));
}
@@ -114085,7 +116190,7 @@
ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined;
});
var contextualType = checker.getContextualType(call);
- var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker) || ts.createKeywordTypeNode(120 /* AnyKeyword */);
+ var returnType = (inJs || !contextualType) ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker);
return ts.createMethod(
/*decorators*/ undefined,
/*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined,
@@ -114121,8 +116226,8 @@
var maxArgsSignature = signatures[0];
var minArgumentCount = signatures[0].minArgumentCount;
var someSigHasRestParameter = false;
- for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
- var sig = signatures_8[_i];
+ for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
+ var sig = signatures_2[_i];
minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount);
if (sig.hasRestParameter) {
someSigHasRestParameter = true;
@@ -114281,8 +116386,8 @@
ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport));
}
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"), {}); });
+ var sourceFile_1 = context.sourceFile;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_1, expr, ts.createPropertyAccess(expr, "default"), {}); });
fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member));
}
return fixes;
@@ -114420,6 +116525,7 @@
return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings));
}
ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText;
+ /* @internal */
var OutputKind;
(function (OutputKind) {
OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals";
@@ -114554,16 +116660,16 @@
}
}
function toPropertyName(name) {
- return ts.isIdentifierText(name, 6 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name);
+ return ts.isIdentifierText(name, 7 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name);
}
// Parses assignments to "this.x" in the constructor into class property declarations
function getConstructorFunctionInstanceProperties(fnAst, members) {
forEachOwnNodeOfFunction(fnAst, function (node) {
if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) &&
ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) {
- var name_7 = node.left.name.text;
- if (!ts.isJsPrivate(name_7)) {
- ts.getOrUpdate(members, name_7, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_7, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); });
+ var name_4 = node.left.name.text;
+ if (!ts.isJsPrivate(name_4)) {
+ ts.getOrUpdate(members, name_4, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_4, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); });
}
}
});
@@ -114598,7 +116704,7 @@
}
function parseExpression(expr) {
var text = "const _ = " + expr;
- var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true);
+ var srcFile = ts.createSourceFile("test.ts", text, 7 /* Latest */, /*setParentNodes*/ true);
return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer;
}
function inferParameterType(_fn, _param) {
@@ -114615,7 +116721,7 @@
}
function isValidIdentifier(name) {
var keyword = ts.stringToToken(name);
- return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */);
+ return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 7 /* ESNext */);
}
function addComment(node, comment) {
if (comment !== undefined)
@@ -115070,7 +117176,7 @@
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 preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 7 /* 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);
@@ -115078,7 +117184,7 @@
});
var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName;
var neededNamedImports = [];
- var _loop_23 = function (element) {
+ var _loop_13 = 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);
@@ -115097,7 +117203,7 @@
};
for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) {
var element = _a[_i];
- _loop_23(element);
+ _loop_13(element);
}
changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName)));
if (neededNamedImports.length) {
@@ -115587,7 +117693,7 @@
// * Module/namespace or source file
if (isScope(current)) {
scopes.push(current);
- if (current.kind === 279 /* SourceFile */) {
+ if (current.kind === 284 /* SourceFile */) {
return scopes;
}
}
@@ -116152,8 +118258,8 @@
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_7 = members; _i < members_7.length; _i++) {
- var member = members_7[_i];
+ for (var _i = 0, members_2 = members; _i < members_2.length; _i++) {
+ var member = members_2[_i];
if (member.pos > maxPos) {
return prevMember || members[0];
}
@@ -116327,7 +118433,7 @@
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_24 = function (i) {
+ var _loop_14 = 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
@@ -116367,7 +118473,7 @@
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_24(i);
+ _loop_14(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
function isInGenericContext(node) {
@@ -116601,7 +118707,7 @@
function isBlockLike(node) {
switch (node.kind) {
case 218 /* Block */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 245 /* ModuleBlock */:
case 271 /* CaseClause */:
return true;
@@ -116918,10 +119024,10 @@
}
function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
var checker = program.getTypeChecker();
- var _loop_25 = function (sourceFile) {
+ var _loop_15 = function (sourceFile) {
if (sourceFile === oldFile)
return "continue";
- var _loop_26 = function (statement) {
+ var _loop_16 = function (statement) {
forEachImportInStatement(statement, function (importNode) {
if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol)
return;
@@ -116943,12 +119049,12 @@
};
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
var statement = _a[_i];
- _loop_26(statement);
+ _loop_16(statement);
}
};
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
- _loop_25(sourceFile);
+ _loop_15(sourceFile);
}
}
function getNamespaceLikeImport(node) {
@@ -116965,7 +119071,7 @@
}
}
function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) {
- var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */);
+ var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 7 /* ESNext */);
var needUniqueName = false;
var toChange = [];
ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) {
@@ -117063,9 +119169,9 @@
if (isTopLevelDeclarationStatement(statement) &&
!isExported(sourceFile, statement, useEs6Exports) &&
forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) {
- var exports_2 = addExport(statement, useEs6Exports);
- if (exports_2)
- return exports_2;
+ var exports = addExport(statement, useEs6Exports);
+ if (exports)
+ return exports;
}
return statement;
});
@@ -117191,7 +119297,7 @@
var movedSymbols = new SymbolSet();
var oldImportsNeededByNewFile = new SymbolSet();
var newFileImportsFromOldFile = new SymbolSet();
- var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 4 /* ContainsJsx */); });
+ var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 2 /* ContainsJsx */); });
var jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx);
if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code)
oldImportsNeededByNewFile.add(jsxNamespaceSymbol);
@@ -117225,7 +119331,7 @@
if (ts.contains(toMove, statement))
continue;
// jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile.
- if (jsxNamespaceSymbol && !!(statement.transformFlags & 4 /* ContainsJsx */)) {
+ if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) {
unusedImportsFromOldFile.delete(jsxNamespaceSymbol);
}
forEachReference(statement, checker, function (symbol) {
@@ -117540,13 +119646,13 @@
var returnStatement_1 = ts.createReturn(expression);
body = ts.createBlock([returnStatement_1], /* multiLine */ true);
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
+ ts.copyLeadingComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
}
else if (actionName === removeBracesActionName && returnStatement) {
var actualExpression = expression || ts.createVoidZero();
body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression;
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
+ ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
}
else {
ts.Debug.fail("invalid action");
@@ -117585,6 +119691,459 @@
})(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var convertParamsToDestructuredObject;
+ (function (convertParamsToDestructuredObject) {
+ var refactorName = "Convert parameters to destructured object";
+ var minimumParameterLength = 2;
+ refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
+ function getAvailableActions(context) {
+ var file = context.file, startPosition = context.startPosition;
+ var isJSFile = ts.isSourceFileJS(file);
+ if (isJSFile)
+ return ts.emptyArray; // TODO: GH#30113
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
+ if (!functionDeclaration)
+ return ts.emptyArray;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_parameters_to_destructured_object);
+ return [{
+ name: refactorName,
+ description: description,
+ actions: [{
+ name: refactorName,
+ description: description
+ }]
+ }];
+ }
+ function getEditsForAction(context, actionName) {
+ ts.Debug.assert(actionName === refactorName);
+ var file = context.file, startPosition = context.startPosition, program = context.program, cancellationToken = context.cancellationToken, host = context.host;
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker());
+ if (!functionDeclaration || !cancellationToken)
+ return undefined;
+ var groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken);
+ if (groupedReferences.valid) {
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(file, program, host, t, functionDeclaration, groupedReferences); });
+ return { renameFilename: undefined, renameLocation: undefined, edits: edits };
+ }
+ return { edits: [] }; // TODO: GH#30113
+ }
+ function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) {
+ var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); });
+ changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ",
+ // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
+ indentation: 0,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include
+ });
+ var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); });
+ for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) {
+ var call = functionCalls_1[_i];
+ if (call.arguments && call.arguments.length) {
+ var newArgument = ts.getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true);
+ changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include });
+ }
+ }
+ }
+ function getGroupedReferences(functionDeclaration, program, cancellationToken) {
+ var functionNames = getFunctionNames(functionDeclaration);
+ var classNames = ts.isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
+ var names = ts.deduplicate(functionNames.concat(classNames), ts.equateValues);
+ var checker = program.getTypeChecker();
+ var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); });
+ var groupedReferences = groupReferences(references);
+ if (!ts.every(groupedReferences.declarations, /*callback*/ function (/*callback*/ decl) { return ts.contains(names, decl); })) {
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ function groupReferences(referenceEntries) {
+ var classReferences = { accessExpressions: [], typeUsages: [] };
+ var groupedReferences = { functionCalls: [], declarations: [], classReferences: classReferences, valid: true };
+ var functionSymbols = ts.map(functionNames, checker.getSymbolAtLocation);
+ var classSymbols = ts.map(classNames, checker.getSymbolAtLocation);
+ var isConstructor = ts.isConstructorDeclaration(functionDeclaration);
+ for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
+ var entry = referenceEntries_1[_i];
+ if (entry.kind !== 1 /* Node */) {
+ groupedReferences.valid = false;
+ continue;
+ }
+ /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function.
+ Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test:
+ class A { foo(a: number, b: number) { return a + b; } }
+ class B { foo(c: number, d: number) { return c + d; } }
+ declare const ab: A | B;
+ ab.foo(1, 2);
+ Find all references will return `ab.foo(1, 2)` as a reference to A's `foo` but we could be calling B's `foo`.
+ When looking for constructor calls, however, the symbol on the constructor call reference is going to be the corresponding class symbol.
+ So we need to add a special case for this because when calling a constructor of a class through one of its subclasses,
+ the symbols are going to be different.
+ */
+ if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer) || ts.isNewExpressionTarget(entry.node)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var call = entryToFunctionCall(entry);
+ if (call) {
+ groupedReferences.functionCalls.push(call);
+ continue;
+ }
+ }
+ // if the refactored function is a constructor, we must also check if the references to its class are valid
+ if (isConstructor && ts.contains(classSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var accessExpression = entryToAccessExpression(entry);
+ if (accessExpression) {
+ classReferences.accessExpressions.push(accessExpression);
+ continue;
+ }
+ // Only class declarations are allowed to be used as a type (in a heritage clause),
+ // otherwise `findAllReferences` might not be able to track constructor calls.
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ var type = entryToType(entry);
+ if (type) {
+ classReferences.typeUsages.push(type);
+ continue;
+ }
+ }
+ }
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ }
+ }
+ function symbolComparer(a, b) {
+ return ts.getSymbolTarget(a) === ts.getSymbolTarget(b);
+ }
+ function entryToDeclaration(entry) {
+ if (ts.isDeclaration(entry.node.parent)) {
+ return entry.node;
+ }
+ return undefined;
+ }
+ function entryToFunctionCall(entry) {
+ if (entry.node.parent) {
+ var functionReference = entry.node;
+ var parent = functionReference.parent;
+ switch (parent.kind) {
+ // Function call (foo(...) or super(...))
+ case 191 /* CallExpression */:
+ var callExpression = ts.tryCast(parent, ts.isCallExpression);
+ if (callExpression && callExpression.expression === functionReference) {
+ return callExpression;
+ }
+ break;
+ // Constructor call (new Foo(...))
+ case 192 /* NewExpression */:
+ var newExpression = ts.tryCast(parent, ts.isNewExpression);
+ if (newExpression && newExpression.expression === functionReference) {
+ return newExpression;
+ }
+ break;
+ // Method call (x.foo(...))
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) {
+ var callExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_1 && callExpression_1.expression === propertyAccessExpression) {
+ return callExpression_1;
+ }
+ }
+ break;
+ // Method call (x["foo"](...))
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) {
+ var callExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_2 && callExpression_2.expression === elementAccessExpression) {
+ return callExpression_2;
+ }
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToAccessExpression(entry) {
+ if (entry.node.parent) {
+ var reference = entry.node;
+ var parent = reference.parent;
+ switch (parent.kind) {
+ // `C.foo`
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.expression === reference) {
+ return propertyAccessExpression;
+ }
+ break;
+ // `C["foo"]`
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.expression === reference) {
+ return elementAccessExpression;
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToType(entry) {
+ var reference = entry.node;
+ if (ts.getMeaningFromLocation(reference) === 2 /* Type */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) {
+ return reference;
+ }
+ return undefined;
+ }
+ function getFunctionDeclarationAtPosition(file, startPosition, checker) {
+ var node = ts.getTouchingToken(file, startPosition);
+ var functionDeclaration = ts.getContainingFunction(node);
+ // don't offer refactor on top-level JSDoc
+ if (isTopLevelJSDoc(node))
+ return undefined;
+ if (functionDeclaration
+ && isValidFunctionDeclaration(functionDeclaration, checker)
+ && ts.rangeContainsRange(functionDeclaration, node)
+ && !(functionDeclaration.body && ts.rangeContainsRange(functionDeclaration.body, node)))
+ return functionDeclaration;
+ return undefined;
+ }
+ function isTopLevelJSDoc(node) {
+ var containingJSDoc = ts.findAncestor(node, ts.isJSDocNode);
+ if (containingJSDoc) {
+ var containingNonJSDoc = ts.findAncestor(containingJSDoc, function (n) { return !ts.isJSDocNode(n); });
+ return !!containingNonJSDoc && ts.isFunctionLikeDeclaration(containingNonJSDoc);
+ }
+ return false;
+ }
+ function isValidFunctionDeclaration(functionDeclaration, checker) {
+ if (!isValidParameterNodeArray(functionDeclaration.parameters, checker))
+ return false;
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return !!functionDeclaration.name
+ && !!functionDeclaration.body
+ && !checker.isImplementationOfOverload(functionDeclaration);
+ case 157 /* Constructor */:
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ return !!functionDeclaration.body
+ && !!functionDeclaration.parent.name
+ && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ else {
+ return isValidVariableDeclaration(functionDeclaration.parent.parent)
+ && !!functionDeclaration.body
+ && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ case 196 /* FunctionExpression */:
+ case 197 /* ArrowFunction */:
+ return isValidVariableDeclaration(functionDeclaration.parent);
+ }
+ return false;
+ }
+ function isValidParameterNodeArray(parameters, checker) {
+ return getRefactorableParametersLength(parameters) >= minimumParameterLength
+ && ts.every(parameters, /*callback*/ function (/*callback*/ paramDecl) { return isValidParameterDeclaration(paramDecl, checker); });
+ }
+ function isValidParameterDeclaration(parameterDeclaration, checker) {
+ if (ts.isRestParameter(parameterDeclaration)) {
+ var type = checker.getTypeAtLocation(parameterDeclaration);
+ if (!checker.isArrayType(type) && !checker.isTupleType(type))
+ return false;
+ }
+ return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name);
+ }
+ function isValidVariableDeclaration(node) {
+ return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113
+ }
+ function hasThisParameter(parameters) {
+ return parameters.length > 0 && ts.isThis(parameters[0].name);
+ }
+ function getRefactorableParametersLength(parameters) {
+ if (hasThisParameter(parameters)) {
+ return parameters.length - 1;
+ }
+ return parameters.length;
+ }
+ function getRefactorableParameters(parameters) {
+ if (hasThisParameter(parameters)) {
+ parameters = ts.createNodeArray(parameters.slice(1), parameters.hasTrailingComma);
+ }
+ return parameters;
+ }
+ function createPropertyOrShorthandAssignment(name, initializer) {
+ if (ts.isIdentifier(initializer) && ts.getTextOfIdentifierOrLiteral(initializer) === name) {
+ return ts.createShorthandPropertyAssignment(name);
+ }
+ return ts.createPropertyAssignment(name, initializer);
+ }
+ function createNewArgument(functionDeclaration, functionArguments) {
+ var parameters = getRefactorableParameters(functionDeclaration.parameters);
+ var hasRestParameter = ts.isRestParameter(ts.last(parameters));
+ var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments;
+ var properties = ts.map(nonRestArguments, function (arg, i) {
+ var parameterName = getParameterName(parameters[i]);
+ var property = createPropertyOrShorthandAssignment(parameterName, arg);
+ ts.suppressLeadingAndTrailingTrivia(property.name);
+ if (ts.isPropertyAssignment(property))
+ ts.suppressLeadingAndTrailingTrivia(property.initializer);
+ copyComments(arg, property);
+ return property;
+ });
+ if (hasRestParameter && functionArguments.length >= parameters.length) {
+ var restArguments = functionArguments.slice(parameters.length - 1);
+ var restProperty = ts.createPropertyAssignment(getParameterName(ts.last(parameters)), ts.createArrayLiteral(restArguments));
+ properties.push(restProperty);
+ }
+ var objectLiteral = ts.createObjectLiteral(properties, /*multiLine*/ false);
+ return objectLiteral;
+ }
+ function createNewParameters(functionDeclaration, program, host) {
+ var checker = program.getTypeChecker();
+ var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters);
+ var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration);
+ var objectParameterName = ts.createObjectBindingPattern(bindingElements);
+ var objectParameterType = createParameterTypeNode(refactorableParameters);
+ var objectInitializer;
+ // If every parameter in the original function was optional, add an empty object initializer to the new object parameter
+ if (ts.every(refactorableParameters, isOptionalParameter)) {
+ objectInitializer = ts.createObjectLiteral();
+ }
+ var objectParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, objectParameterName,
+ /*questionToken*/ undefined, objectParameterType, objectInitializer);
+ if (hasThisParameter(functionDeclaration.parameters)) {
+ var thisParameter = functionDeclaration.parameters[0];
+ var newThisParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, thisParameter.name,
+ /*questionToken*/ undefined, thisParameter.type);
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.name);
+ copyComments(thisParameter.name, newThisParameter.name);
+ if (thisParameter.type) {
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.type);
+ copyComments(thisParameter.type, newThisParameter.type);
+ }
+ return ts.createNodeArray([newThisParameter, objectParameter]);
+ }
+ return ts.createNodeArray([objectParameter]);
+ function createBindingElementFromParameterDeclaration(parameterDeclaration) {
+ var element = ts.createBindingElement(
+ /*dotDotDotToken*/ undefined,
+ /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer);
+ ts.suppressLeadingAndTrailingTrivia(element);
+ if (parameterDeclaration.initializer && element.initializer) {
+ copyComments(parameterDeclaration.initializer, element.initializer);
+ }
+ return element;
+ }
+ function createParameterTypeNode(parameters) {
+ var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration);
+ var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */);
+ return typeNode;
+ }
+ function createPropertySignatureFromParameterDeclaration(parameterDeclaration) {
+ var parameterType = parameterDeclaration.type;
+ if (!parameterType && (parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration))) {
+ parameterType = getTypeNode(parameterDeclaration);
+ }
+ var propertySignature = ts.createPropertySignature(
+ /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType,
+ /*initializer*/ undefined);
+ ts.suppressLeadingAndTrailingTrivia(propertySignature);
+ copyComments(parameterDeclaration.name, propertySignature.name);
+ if (parameterDeclaration.type && propertySignature.type) {
+ copyComments(parameterDeclaration.type, propertySignature.type);
+ }
+ return propertySignature;
+ }
+ function getTypeNode(node) {
+ var type = checker.getTypeAtLocation(node);
+ return ts.getTypeNodeIfAccessible(type, node, program, host);
+ }
+ function isOptionalParameter(parameterDeclaration) {
+ if (ts.isRestParameter(parameterDeclaration)) {
+ var type = checker.getTypeAtLocation(parameterDeclaration);
+ return !checker.isTupleType(type);
+ }
+ return checker.isOptionalParameter(parameterDeclaration);
+ }
+ }
+ function copyComments(sourceNode, targetNode) {
+ var sourceFile = sourceNode.getSourceFile();
+ var text = sourceFile.text;
+ if (hasLeadingLineBreak(sourceNode, text)) {
+ ts.copyLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ else {
+ ts.copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ ts.copyTrailingComments(sourceNode, targetNode, sourceFile);
+ }
+ function hasLeadingLineBreak(node, text) {
+ var start = node.getFullStart();
+ var end = node.getStart();
+ for (var i = start; i < end; i++) {
+ if (text.charCodeAt(i) === 10 /* lineFeed */)
+ return true;
+ }
+ return false;
+ }
+ function getParameterName(paramDeclaration) {
+ return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name);
+ }
+ function getClassNames(constructorDeclaration) {
+ switch (constructorDeclaration.parent.kind) {
+ case 240 /* ClassDeclaration */:
+ var classDeclaration = constructorDeclaration.parent;
+ return [classDeclaration.name];
+ case 209 /* ClassExpression */:
+ var classExpression = constructorDeclaration.parent;
+ var variableDeclaration = constructorDeclaration.parent.parent;
+ var className = classExpression.name;
+ if (className)
+ return [className, variableDeclaration.name];
+ return [variableDeclaration.name];
+ }
+ }
+ function getFunctionNames(functionDeclaration) {
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return [functionDeclaration.name];
+ case 157 /* Constructor */:
+ var ctrKeyword = ts.findChildOfKind(functionDeclaration, 124 /* ConstructorKeyword */, functionDeclaration.getSourceFile());
+ if (functionDeclaration.parent.kind === 209 /* ClassExpression */) {
+ var variableDeclaration = functionDeclaration.parent.parent;
+ return [variableDeclaration.name, ctrKeyword];
+ }
+ return [ctrKeyword];
+ case 197 /* ArrowFunction */:
+ return [functionDeclaration.parent.name];
+ case 196 /* FunctionExpression */:
+ if (functionDeclaration.name)
+ return [functionDeclaration.name, functionDeclaration.parent.name];
+ return [functionDeclaration.parent.name];
+ default:
+ return ts.Debug.assertNever(functionDeclaration);
+ }
+ }
+ })(convertParamsToDestructuredObject = refactor.convertParamsToDestructuredObject || (refactor.convertParamsToDestructuredObject = {}));
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
var ts;
(function (ts) {
/** The version of the language service API */
@@ -117602,7 +120161,8 @@
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
- this.transformFlags = undefined; // TODO: GH#18217
+ this.modifierFlagsCache = 0 /* None */;
+ this.transformFlags = 0 /* None */;
this.parent = undefined;
this.kind = kind;
}
@@ -117664,7 +120224,7 @@
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 288 /* FirstJSDocNode */ || kid.kind > 310 /* LastJSDocNode */; });
return child.kind < 148 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -117734,11 +120294,11 @@
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(311 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
- for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) {
- var node = nodes_7[_i];
+ for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
+ var node = nodes_1[_i];
addSyntheticNodes(list._children, pos, node.pos, parent);
list._children.push(node);
pos = node.end;
@@ -117752,6 +120312,8 @@
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
+ this.modifierFlagsCache = 0 /* None */;
+ this.transformFlags = 0 /* None */;
this.parent = undefined;
}
TokenOrIdentifierObject.prototype.getSourceFile = function () {
@@ -117980,8 +120542,8 @@
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_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)
@@ -118327,7 +120889,7 @@
var sourceFile;
if (this.currentFileName !== fileName) {
// This is a new file, just parse it
- sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 6 /* Latest */, version, /*setNodeParents*/ true, scriptKind);
+ sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 7 /* Latest */, version, /*setNodeParents*/ true, scriptKind);
}
else if (this.currentFileVersion !== version) {
// This is the same file, just a newer version. Incrementally parse the file.
@@ -118451,9 +121013,9 @@
}());
ts.ThrottledCancellationToken = ThrottledCancellationToken;
function createLanguageService(host, documentRegistry, syntaxOnly) {
+ var _a;
if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); }
if (syntaxOnly === void 0) { syntaxOnly = false; }
- var _a;
var syntaxTreeCache = new SyntaxTreeCache(host);
var program;
var lastProjectVersion;
@@ -118484,7 +121046,7 @@
function getValidSourceFile(fileName) {
var sourceFile = program.getSourceFile(fileName);
if (!sourceFile) {
- throw new Error("Could not find file: '" + fileName + "'.");
+ throw new Error("Could not find sourceFile: '" + fileName + "' in " + (program && JSON.stringify(program.getSourceFiles().map(function (f) { return f.fileName; }))) + ".");
}
return sourceFile;
}
@@ -118733,14 +121295,14 @@
var typeChecker = program.getTypeChecker();
var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker);
if (!symbol || typeChecker.isUnknownSymbol(symbol)) {
- var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined;
- return type_7 && {
+ 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_7, ts.getContainerNode(node)); }),
- documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined,
- tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined
+ 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) {
@@ -120851,4 +123413,5 @@
// TODO: it should be moved into a namespace though.
/* @internal */
var toolsVersion = ts.versionMajorMinor;
-//# sourceMappingURL=typescriptServices.out.js.map
\ No newline at end of file
+
+//# sourceMappingURL=typescriptServices.js.map

lib/typingsInstaller.js

@@ -15,31 +15,6 @@
"use strict";
-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 __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];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
@@ -82,13 +57,26 @@
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.3";
+ ts.versionMajorMinor = "3.4";
/** The version of the TypeScript compiler release */
- ts.version = ts.versionMajorMinor + ".4000";
+ ts.version = ts.versionMajorMinor + ".5";
})(ts || (ts = {}));
(function (ts) {
/* @internal */
@@ -144,19 +132,25 @@
// Keep the class inside a function so it doesn't get compiled if it's not used.
function shimMap() {
var MapIterator = /** @class */ (function () {
- function MapIterator(data, selector) {
- this.index = 0;
- this.data = data;
+ function MapIterator(currentEntry, selector) {
+ this.currentEntry = currentEntry;
this.selector = selector;
- this.keys = Object.keys(data);
}
MapIterator.prototype.next = function () {
- var index = this.index;
- if (index < this.keys.length) {
- this.index++;
- return { value: this.selector(this.data, this.keys[index]), done: false };
+ // Navigate to the next entry.
+ while (this.currentEntry) {
+ var skipNext = !!this.currentEntry.skipNext;
+ this.currentEntry = this.currentEntry.nextEntry;
+ if (!skipNext) {
+ break;
+ }
+ }
+ if (this.currentEntry) {
+ return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false };
}
+ else {
return { value: undefined, done: true };
+ }
};
return MapIterator;
}());
@@ -164,15 +158,36 @@
function class_1() {
this.data = createDictionaryObject();
this.size = 0;
+ // Create a first (stub) map entry that will not contain a key
+ // and value but serves as starting point for iterators.
+ this.firstEntry = {};
+ // When the map is empty, the last entry is the same as the
+ // first one.
+ this.lastEntry = this.firstEntry;
}
class_1.prototype.get = function (key) {
- return this.data[key];
+ var entry = this.data[key];
+ return entry && entry.value;
};
class_1.prototype.set = function (key, value) {
if (!this.has(key)) {
this.size++;
+ // Create a new entry that will be appended at the
+ // end of the linked list.
+ var newEntry = {
+ key: key,
+ value: value
+ };
+ this.data[key] = newEntry;
+ // Adjust the references.
+ var previousLastEntry = this.lastEntry;
+ previousLastEntry.nextEntry = newEntry;
+ newEntry.previousEntry = previousLastEntry;
+ this.lastEntry = newEntry;
+ }
+ else {
+ this.data[key].value = value;
}
- this.data[key] = value;
return this;
};
class_1.prototype.has = function (key) {
@@ -182,7 +197,28 @@
class_1.prototype.delete = function (key) {
if (this.has(key)) {
this.size--;
+ var entry = this.data[key];
delete this.data[key];
+ // Adjust the linked list references of the neighbor entries.
+ var previousEntry = entry.previousEntry;
+ previousEntry.nextEntry = entry.nextEntry;
+ if (entry.nextEntry) {
+ entry.nextEntry.previousEntry = previousEntry;
+ }
+ // When the deleted entry was the last one, we need to
+ // adust the lastEntry reference.
+ if (this.lastEntry === entry) {
+ this.lastEntry = previousEntry;
+ }
+ // Adjust the forward reference of the deleted entry
+ // in case an iterator still references it. This allows us
+ // to throw away the entry, but when an active iterator
+ // (which points to the current entry) continues, it will
+ // navigate to the entry that originally came before the
+ // current one and skip it.
+ entry.previousEntry = undefined;
+ entry.nextEntry = previousEntry;
+ entry.skipNext = true;
return true;
}
return false;
@@ -190,24 +226,46 @@
class_1.prototype.clear = function () {
this.data = createDictionaryObject();
this.size = 0;
+ // Reset the linked list. Note that we must adjust the forward
+ // references of the deleted entries to ensure iterators stuck
+ // in the middle of the list don't continue with deleted entries,
+ // but can continue with new entries added after the clear()
+ // operation.
+ var firstEntry = this.firstEntry;
+ var currentEntry = firstEntry.nextEntry;
+ while (currentEntry) {
+ var nextEntry = currentEntry.nextEntry;
+ currentEntry.previousEntry = undefined;
+ currentEntry.nextEntry = firstEntry;
+ currentEntry.skipNext = true;
+ currentEntry = nextEntry;
+ }
+ firstEntry.nextEntry = undefined;
+ this.lastEntry = firstEntry;
};
class_1.prototype.keys = function () {
- return new MapIterator(this.data, function (_data, key) { return key; });
+ return new MapIterator(this.firstEntry, function (key) { return key; });
};
class_1.prototype.values = function () {
- return new MapIterator(this.data, function (data, key) { return data[key]; });
+ return new MapIterator(this.firstEntry, function (_key, value) { return value; });
};
class_1.prototype.entries = function () {
- return new MapIterator(this.data, function (data, key) { return [key, data[key]]; });
+ return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; });
};
class_1.prototype.forEach = function (action) {
- for (var key in this.data) {
- action(this.data[key], key);
+ var iterator = this.entries();
+ while (true) {
+ var _a = iterator.next(), entry = _a.value, done = _a.done;
+ if (done) {
+ break;
+ }
+ action(entry[1], entry[0]);
}
};
return class_1;
}());
}
+ ts.shimMap = shimMap;
function length(array) {
return array ? array.length : 0;
}
@@ -755,7 +813,7 @@
}
/**
* Deduplicates an unsorted array.
- * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates.
+ * @param equalityComparer An `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`.
*/
@@ -971,6 +1029,21 @@
} };
}
ts.arrayIterator = arrayIterator;
+ function arrayReverseIterator(array) {
+ var i = array.length;
+ return {
+ next: function () {
+ if (i === 0) {
+ return { value: undefined, done: true };
+ }
+ else {
+ i--;
+ return { value: array[i], done: false };
+ }
+ }
+ };
+ }
+ ts.arrayReverseIterator = arrayReverseIterator;
/**
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
*/
@@ -1181,9 +1254,11 @@
}
for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
var arg = args_1[_a];
+ if (arg === undefined)
+ continue;
for (var p in arg) {
if (hasProperty(arg, p)) {
- t[p] = arg[p]; // TODO: GH#23368
+ t[p] = arg[p];
}
}
}
@@ -1359,6 +1434,9 @@
/** Do nothing and return true */
function returnTrue() { return true; }
ts.returnTrue = returnTrue;
+ /** Do nothing and return undefined */
+ function returnUndefined() { return undefined; }
+ ts.returnUndefined = returnUndefined;
/** Returns its argument. */
function identity(x) { return x; }
ts.identity = identity;
@@ -1505,7 +1583,7 @@
Debug.assertEachDefined = assertEachDefined;
function assertNever(member, message, stackCrawlMark) {
if (message === void 0) { message = "Illegal value:"; }
- var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member);
+ var detail = typeof member === "object" && "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member);
return fail(message + " " + detail, stackCrawlMark || assertNever);
}
Debug.assertNever = assertNever;
@@ -2808,47 +2886,53 @@
SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment";
// Enum
SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember";
+ // Unparsed
+ SyntaxKind[SyntaxKind["UnparsedPrologue"] = 279] = "UnparsedPrologue";
+ SyntaxKind[SyntaxKind["UnparsedPrepend"] = 280] = "UnparsedPrepend";
+ SyntaxKind[SyntaxKind["UnparsedText"] = 281] = "UnparsedText";
+ SyntaxKind[SyntaxKind["UnparsedInternalText"] = 282] = "UnparsedInternalText";
+ SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 283] = "UnparsedSyntheticReference";
// Top-level nodes
- SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile";
- SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle";
- SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource";
- SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles";
+ SyntaxKind[SyntaxKind["SourceFile"] = 284] = "SourceFile";
+ SyntaxKind[SyntaxKind["Bundle"] = 285] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 286] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 287] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 288] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 289] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature";
- SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag";
- SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 290] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 291] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 292] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 293] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 294] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 295] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 296] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 297] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocSignature"] = 298] = "JSDocSignature";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 299] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 300] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 301] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 302] = "JSDocCallbackTag";
+ SyntaxKind[SyntaxKind["JSDocEnumTag"] = 303] = "JSDocEnumTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 304] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 305] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocThisTag"] = 306] = "JSDocThisTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 307] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 308] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 309] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 310] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 311] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 312] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 313] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 314] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 315] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 316] = "EndOfDeclarationMarker";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 312] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 317] = "Count";
// Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment";
@@ -2875,10 +2959,10 @@
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator";
SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 288] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 310] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 299] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 310] = "LastJSDocTagNode";
/* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword";
/* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
@@ -2985,21 +3069,27 @@
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
})(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
- /* @internal */
var TokenFlags;
(function (TokenFlags) {
TokenFlags[TokenFlags["None"] = 0] = "None";
+ /* @internal */
TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
+ /* @internal */
TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
+ /* @internal */
TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
+ /* @internal */
TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
+ /* @internal */
TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
+ /* @internal */
TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
+ /* @internal */
TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
})(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
var FlowFlags;
@@ -3359,12 +3449,6 @@
TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
/* @internal */
- TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType";
- /* @internal */
- TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral";
- /* @internal */
- TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType";
- /* @internal */
TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
/* @internal */
TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
@@ -3396,28 +3480,29 @@
TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive";
TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable";
TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable";
+ /* @internal */
+ TypeFlags[TypeFlags["ObjectFlagsType"] = 3899392] = "ObjectFlagsType";
// 'Narrowable' types are types where narrowing actually narrows.
// This *should* be every type other than null, undefined, void, and never
TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable";
TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit";
/* @internal */
TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion";
+ // The following flags are aggregated during union and intersection type construction
/* @internal */
- TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening";
- /* @internal */
- TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags";
+ TypeFlags[TypeFlags["IncludesMask"] = 1835007] = "IncludesMask";
// The following flags are used for different purposes during union and intersection type construction
/* @internal */
- TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType";
+ TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
/* @internal */
- TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard";
+ TypeFlags[TypeFlags["IncludesNonWideningType"] = 2097152] = "IncludesNonWideningType";
/* @internal */
- TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject";
+ TypeFlags[TypeFlags["IncludesWildcard"] = 4194304] = "IncludesWildcard";
/* @internal */
- TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags";
+ TypeFlags[TypeFlags["IncludesEmptyObject"] = 8388608] = "IncludesEmptyObject";
// The following flag is used for different purposes by maybeTypeOfKind
/* @internal */
- TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType";
+ TypeFlags[TypeFlags["GenericMappedType"] = 131072] = "GenericMappedType";
})(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
var ObjectFlags;
(function (ObjectFlags) {
@@ -3437,7 +3522,19 @@
ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
+ /* @internal */
+ ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion";
+ /* @internal */
+ ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType";
+ /* @internal */
+ ObjectFlags[ObjectFlags["ContainsObjectLiteral"] = 262144] = "ContainsObjectLiteral";
+ /* @internal */
+ ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType";
ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
+ /* @internal */
+ ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening";
+ /* @internal */
+ ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags";
})(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
/* @internal */
var Variance;
@@ -3482,6 +3579,7 @@
InferenceFlags[InferenceFlags["None"] = 0] = "None";
InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
+ InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
})(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
/**
* Ternary values are defined such that
@@ -3589,9 +3687,10 @@
ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
- ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext";
+ ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
+ ScriptTarget[ScriptTarget["ESNext"] = 7] = "ESNext";
ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
- ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest";
+ ScriptTarget[ScriptTarget["Latest"] = 7] = "Latest";
})(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
var LanguageVariant;
(function (LanguageVariant) {
@@ -3740,6 +3839,7 @@
Extension["Js"] = ".js";
Extension["Jsx"] = ".jsx";
Extension["Json"] = ".json";
+ Extension["TsBuildInfo"] = ".tsbuildinfo";
})(Extension = ts.Extension || (ts.Extension = {}));
/* @internal */
var TransformFlags;
@@ -3747,71 +3847,69 @@
TransformFlags[TransformFlags["None"] = 0] = "None";
// Facts
// - Flags used to indicate that a node or subtree contains syntax that requires transformation.
- TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript";
- TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript";
- TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx";
- TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext";
- TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017";
- TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016";
- TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015";
+ TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
+ TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
+ TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
+ TransformFlags[TransformFlags["ContainsES2019"] = 8] = "ContainsES2019";
+ TransformFlags[TransformFlags["ContainsES2018"] = 16] = "ContainsES2018";
+ TransformFlags[TransformFlags["ContainsES2017"] = 32] = "ContainsES2017";
+ TransformFlags[TransformFlags["ContainsES2016"] = 64] = "ContainsES2016";
TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015";
- TransformFlags[TransformFlags["Generator"] = 256] = "Generator";
- TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
- TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment";
- TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment";
+ TransformFlags[TransformFlags["ContainsGenerator"] = 256] = "ContainsGenerator";
+ TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 512] = "ContainsDestructuringAssignment";
// Markers
// - Flags used to indicate that a subtree contains a specific transformation.
- TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax";
- TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis";
- TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis";
- TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName";
- TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments";
- TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread";
- TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread";
- TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName";
- TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding";
- TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern";
- TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield";
- TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion";
- TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport";
- TransformFlags[TransformFlags["Super"] = 33554432] = "Super";
- TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper";
+ TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 1024] = "ContainsTypeScriptClassSyntax";
+ TransformFlags[TransformFlags["ContainsLexicalThis"] = 2048] = "ContainsLexicalThis";
+ TransformFlags[TransformFlags["ContainsRestOrSpread"] = 4096] = "ContainsRestOrSpread";
+ TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 8192] = "ContainsObjectRestOrSpread";
+ TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 16384] = "ContainsComputedPropertyName";
+ TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 32768] = "ContainsBlockScopedBinding";
+ TransformFlags[TransformFlags["ContainsBindingPattern"] = 65536] = "ContainsBindingPattern";
+ TransformFlags[TransformFlags["ContainsYield"] = 131072] = "ContainsYield";
+ TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 262144] = "ContainsHoistedDeclarationOrCompletion";
+ TransformFlags[TransformFlags["ContainsDynamicImport"] = 524288] = "ContainsDynamicImport";
// Please leave this as 1 << 29.
// It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
// It is a good reminder of how much room we have left
TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
// Assertions
// - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
- TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript";
- TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx";
- TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext";
- TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017";
- TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016";
- TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015";
- TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator";
- TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment";
+ TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
+ TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
+ TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
+ TransformFlags[TransformFlags["AssertES2019"] = 8] = "AssertES2019";
+ TransformFlags[TransformFlags["AssertES2018"] = 16] = "AssertES2018";
+ TransformFlags[TransformFlags["AssertES2017"] = 32] = "AssertES2017";
+ TransformFlags[TransformFlags["AssertES2016"] = 64] = "AssertES2016";
+ TransformFlags[TransformFlags["AssertES2015"] = 128] = "AssertES2015";
+ TransformFlags[TransformFlags["AssertGenerator"] = 256] = "AssertGenerator";
+ TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 512] = "AssertDestructuringAssignment";
// Scope Exclusions
// - Bitmasks that exclude flags from propagating out of a specific context
// into the subtree flags of their container.
- TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes";
- TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes";
- TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes";
- TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes";
- TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes";
- TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes";
- TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes";
- TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes";
- TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes";
- TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes";
- TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes";
- TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes";
- TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes";
- TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes";
- TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes";
- TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes";
+ TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
+ TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
+ TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
+ TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 537371648] = "ArrowFunctionExcludes";
+ TransformFlags[TransformFlags["FunctionExcludes"] = 537373696] = "FunctionExcludes";
+ TransformFlags[TransformFlags["ConstructorExcludes"] = 537372672] = "ConstructorExcludes";
+ TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 537372672] = "MethodOrAccessorExcludes";
+ TransformFlags[TransformFlags["PropertyExcludes"] = 536872960] = "PropertyExcludes";
+ TransformFlags[TransformFlags["ClassExcludes"] = 536888320] = "ClassExcludes";
+ TransformFlags[TransformFlags["ModuleExcludes"] = 537168896] = "ModuleExcludes";
+ TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
+ TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536896512] = "ObjectLiteralExcludes";
+ TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536875008] = "ArrayLiteralOrCallOrNewExcludes";
+ TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 536944640] = "VariableDeclarationListExcludes";
+ TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
+ TransformFlags[TransformFlags["CatchClauseExcludes"] = 536879104] = "CatchClauseExcludes";
+ TransformFlags[TransformFlags["BindingPatternExcludes"] = 536875008] = "BindingPatternExcludes";
+ // Propagating flags
+ // - Bitmasks for flags that should propagate from a child
+ TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 2048] = "PropertyNamePropagatingFlags";
// Masks
// - Additional bitmasks
- TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask";
})(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
var EmitFlags;
(function (EmitFlags) {
@@ -3893,6 +3991,20 @@
EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
})(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
+ /*@internal*/
+ var BundleFileSectionKind;
+ (function (BundleFileSectionKind) {
+ BundleFileSectionKind["Prologue"] = "prologue";
+ BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
+ BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
+ BundleFileSectionKind["Reference"] = "reference";
+ BundleFileSectionKind["Type"] = "type";
+ BundleFileSectionKind["Lib"] = "lib";
+ BundleFileSectionKind["Prepend"] = "prepend";
+ BundleFileSectionKind["Text"] = "text";
+ BundleFileSectionKind["Internal"] = "internal";
+ // comments?
+ })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
var ListFormat;
(function (ListFormat) {
ListFormat[ListFormat["None"] = 0] = "None";
@@ -4039,8 +4151,11 @@
*/
/* @internal */
function generateDjb2Hash(data) {
- var chars = data.split("").map(function (str) { return str.charCodeAt(0); });
- return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381);
+ var acc = 5381;
+ for (var i = 0; i < data.length; i++) {
+ acc = ((acc << 5) + acc) + data.charCodeAt(i);
+ }
+ return acc.toString();
}
ts.generateDjb2Hash = generateDjb2Hash;
/**
@@ -4300,6 +4415,8 @@
: FileWatcherEventKind.Changed;
}
ts.getFileWatcherEventKind = getFileWatcherEventKind;
+ /*@internal*/
+ ts.ignoredPaths = ["/node_modules/.", "/.git"];
/**
* 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
@@ -4324,6 +4441,8 @@
else {
directoryWatcher = {
watcher: host.watchDirectory(dirName, function (fileName) {
+ if (isIgnoredPath(fileName))
+ return;
// Call the actual callback
callbackCache.forEach(function (callbacks, rootDirName) {
if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
@@ -4373,7 +4492,7 @@
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 filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
+ return !isIgnoredPath(childFullName) && 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;
/**
@@ -4390,6 +4509,16 @@
(newChildWatches || (newChildWatches = [])).push(childWatcher);
}
}
+ function isIgnoredPath(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
+ }
+ function isInPath(path, searchPath) {
+ if (ts.stringContains(path, searchPath))
+ return true;
+ if (host.useCaseSensitiveFileNames)
+ return false;
+ return ts.stringContains(toCanonicalFilePath(path), searchPath);
+ }
}
ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher;
function getNodeMajorVersion() {
@@ -4458,8 +4587,18 @@
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!nodeSystem.directoryExists(directoryName)) {
+ // Wrapped in a try-catch to prevent crashing if we are in a race
+ // with another copy of ourselves to create the same directory
+ try {
_fs.mkdirSync(directoryName);
}
+ catch (e) {
+ if (e.code !== "EEXIST") {
+ // Failed for some other reason (access denied?); still throw
+ throw e;
+ }
+ }
+ }
},
getExecutingFilePath: function () {
return __filename;
@@ -4475,7 +4614,7 @@
getModifiedTime: getModifiedTime,
setModifiedTime: setModifiedTime,
deleteFile: deleteFile,
- createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash,
+ createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
createSHA256Hash: _crypto ? createSHA256Hash : undefined,
getMemoryUsage: function () {
if (global.gc) {
@@ -4863,7 +5002,7 @@
}
}
function readDirectory(path, extensions, excludes, includes, depth) {
- return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries);
+ return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
}
function fileSystemEntryExists(path, entryKind) {
try {
@@ -4919,11 +5058,6 @@
return;
}
}
- function createMD5HashUsingNativeCrypto(data) {
- var hash = _crypto.createHash("md5");
- hash.update(data);
- return hash.digest("hex");
- }
function createSHA256Hash(data) {
var hash = _crypto.createHash("sha256");
hash.update(data);
@@ -5184,7 +5318,6 @@
Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."),
Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."),
- Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."),
Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."),
A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."),
Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."),
@@ -5275,6 +5408,8 @@
An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."),
A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."),
A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."),
+ readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types: diag(1354, ts.DiagnosticCategory.Error, "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354", "'readonly' type modifier is only permitted on array and tuple literal types."),
+ A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal: diag(1355, ts.DiagnosticCategory.Error, "A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal_1355", "A 'const' assertion can only be applied to a string, number, boolean, array, or object literal."),
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."),
@@ -5369,7 +5504,7 @@
Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."),
Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
- Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."),
+ This_overload_signature_is_not_compatible_with_its_implementation_signature: diag(2394, ts.DiagnosticCategory.Error, "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394", "This overload signature is not compatible with its implementation signature."),
Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."),
Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."),
Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."),
@@ -5542,15 +5677,20 @@
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."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
- Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."),
Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."),
_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."),
+ Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."),
+ Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
+ Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
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."),
@@ -5657,6 +5797,12 @@
This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."),
This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."),
_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."),
+ Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided: diag(2748, ts.DiagnosticCategory.Error, "Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided_2748", "Cannot access ambient const enums when the '--isolatedModules' flag is provided."),
+ _0_refers_to_a_value_but_is_being_used_as_a_type_here: diag(2749, ts.DiagnosticCategory.Error, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_2749", "'{0}' refers to a value, but is being used as a type here."),
+ The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
+ Circularity_originates_in_type_at_this_location: diag(2751, ts.DiagnosticCategory.Error, "Circularity_originates_in_type_at_this_location_2751", "Circularity originates in type at this location."),
+ The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
+ Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
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}'."),
@@ -5740,6 +5886,7 @@
Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
@@ -5788,7 +5935,7 @@
Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."),
Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
- Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."),
+ Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'."),
Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."),
Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
@@ -6007,6 +6154,16 @@
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."),
Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
+ Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
+ Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
+ A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
+ A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
+ Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
+ Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
+ Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
+ Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
+ Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
+ Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
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."),
The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
@@ -6043,7 +6200,7 @@
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'."),
+ The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."),
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."),
Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),
@@ -6223,6 +6380,7 @@
Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
+ Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
};
})(ts || (ts = {}));
var ts;
@@ -6710,16 +6868,20 @@
return pos;
}
var shebangTriviaRegex = /^#!.*/;
+ /*@internal*/
function isShebangTrivia(text, pos) {
// Shebangs check must only be done at the start of the file
ts.Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
+ ts.isShebangTrivia = isShebangTrivia;
+ /*@internal*/
function scanShebangTrivia(text, pos) {
var shebang = shebangTriviaRegex.exec(text)[0];
pos = pos + shebang.length;
return pos;
}
+ ts.scanShebangTrivia = scanShebangTrivia;
/**
* Invokes a callback for each comment range following the provided position.
*
@@ -6746,8 +6908,15 @@
var pendingKind;
var pendingHasTrailingNewLine;
var hasPendingCommentRange = false;
- var collecting = trailing || pos === 0;
+ var collecting = trailing;
var accumulator = initial;
+ if (pos === 0) {
+ collecting = true;
+ var shebang = getShebang(text);
+ if (shebang) {
+ pos = shebang.length;
+ }
+ }
scan: while (pos >= 0 && pos < text.length) {
var ch = text.charCodeAt(pos);
switch (ch) {
@@ -7982,6 +8151,7 @@
}
pos++;
}
+ tokenValue = text.substring(startPos, pos);
return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
}
// Scans a JSX identifier; these differ from normal identifiers in that
@@ -8063,8 +8233,8 @@
pos++;
return token = 14 /* NoSubstitutionTemplateLiteral */;
}
- if (isIdentifierStart(ch, 6 /* Latest */)) {
- while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) {
+ if (isIdentifierStart(ch, 7 /* Latest */)) {
+ while (isIdentifierPart(text.charCodeAt(pos), 7 /* Latest */) && pos < end) {
pos++;
}
tokenValue = text.substring(tokenPos, pos);
@@ -8422,7 +8592,7 @@
}
}
function getSourceFileOfNode(node) {
- while (node && node.kind !== 279 /* SourceFile */) {
+ while (node && node.kind !== 284 /* SourceFile */) {
node = node.parent;
}
return node;
@@ -8509,10 +8679,7 @@
return !nodeIsMissing(node);
}
ts.nodeIsPresent = nodeIsPresent;
- /**
- * Prepends statements to an array while taking care of prologue directives.
- */
- function addStatementsAfterPrologue(to, from) {
+ function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
if (from === undefined || from.length === 0)
return to;
var statementIndex = 0;
@@ -8525,7 +8692,44 @@
to.splice.apply(to, [statementIndex, 0].concat(from));
return to;
}
- ts.addStatementsAfterPrologue = addStatementsAfterPrologue;
+ function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
+ if (statement === undefined)
+ return to;
+ 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(statementIndex, 0, statement);
+ return to;
+ }
+ function isAnyPrologueDirective(node) {
+ return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
+ }
+ /**
+ * Prepends statements to an array while taking care of prologue directives.
+ */
+ function insertStatementsAfterStandardPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isPrologueDirective);
+ }
+ ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
+ function insertStatementsAfterCustomPrologue(to, from) {
+ return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
+ }
+ ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
+ /**
+ * Prepends statements to an array while taking care of prologue directives.
+ */
+ function insertStatementAfterStandardPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isPrologueDirective);
+ }
+ ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
+ function insertStatementAfterCustomPrologue(to, statement) {
+ return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
+ }
+ ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
/**
* Determine if the given comment is a triple-slash
*
@@ -8568,7 +8772,7 @@
// 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 === 306 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 311 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -8587,7 +8791,7 @@
}
ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
function isJSDocTypeExpressionOrChild(node) {
- return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
+ return node.kind === 288 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
}
function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
@@ -8714,7 +8918,7 @@
return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body);
}
function isBlockScopedContainerTopLevel(node) {
- return node.kind === 279 /* SourceFile */ ||
+ return node.kind === 284 /* SourceFile */ ||
node.kind === 244 /* ModuleDeclaration */ ||
ts.isFunctionLike(node);
}
@@ -8732,7 +8936,7 @@
// - 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 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node.parent);
case 245 /* ModuleBlock */:
return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
@@ -8750,7 +8954,7 @@
ts.isEffectiveExternalModule = isEffectiveExternalModule;
function isBlockScope(node, parentNode) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 274 /* CatchClause */:
case 244 /* ModuleDeclaration */:
@@ -8775,9 +8979,9 @@
ts.isBlockScope = isBlockScope;
function isDeclarationWithTypeParameters(node) {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
- case 293 /* JSDocSignature */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 298 /* JSDocSignature */:
return true;
default:
ts.assertType(node);
@@ -8793,12 +8997,12 @@
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
@@ -8943,7 +9147,7 @@
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* 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
@@ -9118,7 +9322,7 @@
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case 150 /* TypeParameter */:
return node === parent.constraint;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return node === parent.constraint;
case 154 /* PropertyDeclaration */:
case 153 /* PropertySignature */:
@@ -9378,7 +9582,7 @@
}
ts.getContainingClass = getContainingClass;
function getThisContainer(node, includeArrowFunctions) {
- ts.Debug.assert(node.kind !== 279 /* SourceFile */);
+ ts.Debug.assert(node.kind !== 284 /* SourceFile */);
while (true) {
node = node.parent;
if (!node) {
@@ -9432,7 +9636,7 @@
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 243 /* EnumDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return node;
}
}
@@ -9515,6 +9719,11 @@
}
}
ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
+ function isSuperOrSuperProperty(node) {
+ return node.kind === 98 /* SuperKeyword */
+ || isSuperProperty(node);
+ }
+ ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
/**
* Determines whether a node is a property or element access expression for `super`.
*/
@@ -10140,7 +10349,7 @@
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
function isJSDocTypeAlias(node) {
- return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 309 /* JSDocTypedefTag */ || node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocTypeAlias = isJSDocTypeAlias;
function isTypeAlias(node) {
@@ -10284,7 +10493,7 @@
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 === 290 /* JSDocVariadicType */;
+ return node.dotDotDotToken !== undefined || !!type && type.kind === 295 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -10522,14 +10731,15 @@
}
ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
function getEffectiveBaseTypeNode(node) {
- if (isInJSFile(node)) {
+ var baseType = getClassExtendsHeritageElement(node);
+ if (baseType && isInJSFile(node)) {
// Prefer an @augments tag because it may have type parameters.
var tag = ts.getJSDocAugmentsTag(node);
if (tag) {
return tag.class;
}
}
- return getClassExtendsHeritageElement(node);
+ return baseType;
}
ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
function getClassExtendsHeritageElement(node) {
@@ -10768,7 +10978,7 @@
|| kind === 158 /* GetAccessor */
|| kind === 159 /* SetAccessor */
|| kind === 244 /* ModuleDeclaration */
- || kind === 279 /* SourceFile */;
+ || kind === 284 /* SourceFile */;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(range) {
@@ -10845,7 +11055,7 @@
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return 0;
case 208 /* SpreadElement */:
return 1;
@@ -11163,6 +11373,9 @@
lineStart = true;
}
}
+ function getTextPosWithWriteLine() {
+ return lineStart ? output.length : (output.length + newLine.length);
+ }
reset();
return {
write: write,
@@ -11191,7 +11404,8 @@
writeStringLiteral: write,
writeSymbol: function (s, _) { return write(s); },
writeTrailingSemicolon: write,
- writeComment: write
+ writeComment: write,
+ getTextPosWithWriteLine: getTextPosWithWriteLine
};
}
ts.createTextWriter = createTextWriter;
@@ -11320,23 +11534,27 @@
function getSourceFilesToEmit(host, targetSourceFile) {
var options = host.getCompilerOptions();
var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); };
+ var getResolvedProjectReferenceToRedirect = function (fileName) { return host.getResolvedProjectReferenceToRedirect(fileName); };
if (options.outFile || options.out) {
var moduleKind = ts.getEmitModuleKind(options);
var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
// Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
return ts.filter(host.getSourceFiles(), function (sourceFile) {
- return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary);
+ return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect);
});
}
else {
var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
- return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); });
+ return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
}
}
ts.getSourceFilesToEmit = getSourceFilesToEmit;
/** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
- function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) {
- return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile);
+ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect) {
+ return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
+ !sourceFile.isDeclarationFile &&
+ !isSourceFileFromExternalLibrary(sourceFile) &&
+ !(isJsonSourceFile(sourceFile) && getResolvedProjectReferenceToRedirect(sourceFile.fileName));
}
ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
function getSourceFilePathInNewDir(fileName, host, newDirPath) {
@@ -11482,7 +11700,7 @@
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 === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 296 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
}
/**
* Gets the effective type annotation of the value parameter of a set accessor. If the node
@@ -12387,7 +12605,7 @@
}
ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
function getObjectFlags(type) {
- return type.flags & 524288 /* Object */ ? type.objectFlags : 0;
+ return type.flags & 3899392 /* ObjectFlagsType */ ? type.objectFlags : 0;
}
ts.getObjectFlags = getObjectFlags;
function typeHasCallOrConstructSignatures(type, checker) {
@@ -12454,25 +12672,37 @@
|| kind === 96 /* NullKeyword */
|| kind === 132 /* NeverKeyword */
|| kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
+ || kind === 289 /* JSDocAllType */
+ || kind === 290 /* JSDocUnknownType */
+ || kind === 291 /* JSDocNullableType */
+ || kind === 292 /* JSDocNonNullableType */
+ || kind === 293 /* JSDocOptionalType */
+ || kind === 294 /* JSDocFunctionType */
+ || kind === 295 /* JSDocVariadicType */;
}
ts.isTypeNodeKind = isTypeNodeKind;
function isAccessExpression(node) {
return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */;
}
ts.isAccessExpression = isAccessExpression;
+ function isBundleFileTextLike(section) {
+ switch (section.kind) {
+ case "text" /* Text */:
+ case "internal" /* Internal */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isBundleFileTextLike = isBundleFileTextLike;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
switch (options.target) {
- case 6 /* ESNext */:
+ case 7 /* ESNext */:
return "lib.esnext.full.d.ts";
+ case 6 /* ES2019 */:
+ return "lib.es2019.full.d.ts";
case 5 /* ES2018 */:
return "lib.es2018.full.d.ts";
case 4 /* ES2017 */:
@@ -12926,8 +13156,8 @@
switch (declaration.kind) {
case 72 /* Identifier */:
return declaration;
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */: {
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */: {
var name = declaration.name;
if (name.kind === 148 /* QualifiedName */) {
return name.right;
@@ -12951,7 +13181,7 @@
return undefined;
}
}
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
case 254 /* ExportAssignment */: {
var expression = declaration.expression;
@@ -13155,7 +13385,7 @@
return ts.emptyArray;
}
if (ts.isJSDocTypeAlias(node)) {
- ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */);
+ ts.Debug.assert(node.parent.kind === 296 /* JSDocComment */);
return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
}
if (node.typeParameters) {
@@ -13417,12 +13647,17 @@
return node.kind === 194 /* TypeAssertionExpression */;
}
ts.isTypeAssertion = isTypeAssertion;
+ function isConstTypeReference(node) {
+ return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
+ node.typeName.escapedText === "const" && !node.typeArguments;
+ }
+ ts.isConstTypeReference = isConstTypeReference;
function isParenthesizedExpression(node) {
return node.kind === 195 /* ParenthesizedExpression */;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 308 /* PartiallyEmittedExpression */) {
+ while (node.kind === 313 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13769,108 +14004,128 @@
ts.isEnumMember = isEnumMember;
// Top-level nodes
function isSourceFile(node) {
- return node.kind === 279 /* SourceFile */;
+ return node.kind === 284 /* SourceFile */;
}
ts.isSourceFile = isSourceFile;
function isBundle(node) {
- return node.kind === 280 /* Bundle */;
+ return node.kind === 285 /* Bundle */;
}
ts.isBundle = isBundle;
function isUnparsedSource(node) {
- return node.kind === 281 /* UnparsedSource */;
+ return node.kind === 286 /* UnparsedSource */;
}
ts.isUnparsedSource = isUnparsedSource;
+ function isUnparsedPrepend(node) {
+ return node.kind === 280 /* UnparsedPrepend */;
+ }
+ ts.isUnparsedPrepend = isUnparsedPrepend;
+ function isUnparsedTextLike(node) {
+ switch (node.kind) {
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isUnparsedTextLike = isUnparsedTextLike;
+ function isUnparsedNode(node) {
+ return isUnparsedTextLike(node) ||
+ node.kind === 279 /* UnparsedPrologue */ ||
+ node.kind === 283 /* UnparsedSyntheticReference */;
+ }
+ ts.isUnparsedNode = isUnparsedNode;
// JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 283 /* JSDocTypeExpression */;
+ return node.kind === 288 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 284 /* JSDocAllType */;
+ return node.kind === 289 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 285 /* JSDocUnknownType */;
+ return node.kind === 290 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 286 /* JSDocNullableType */;
+ return node.kind === 291 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 287 /* JSDocNonNullableType */;
+ return node.kind === 292 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 288 /* JSDocOptionalType */;
+ return node.kind === 293 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 289 /* JSDocFunctionType */;
+ return node.kind === 294 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 290 /* JSDocVariadicType */;
+ return node.kind === 295 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 291 /* JSDocComment */;
+ return node.kind === 296 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 295 /* JSDocAugmentsTag */;
+ return node.kind === 300 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 296 /* JSDocClassTag */;
+ return node.kind === 301 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocEnumTag(node) {
- return node.kind === 298 /* JSDocEnumTag */;
+ return node.kind === 303 /* JSDocEnumTag */;
}
ts.isJSDocEnumTag = isJSDocEnumTag;
function isJSDocThisTag(node) {
- return node.kind === 301 /* JSDocThisTag */;
+ return node.kind === 306 /* JSDocThisTag */;
}
ts.isJSDocThisTag = isJSDocThisTag;
function isJSDocParameterTag(node) {
- return node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 300 /* JSDocReturnTag */;
+ return node.kind === 305 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 302 /* JSDocTypeTag */;
+ return node.kind === 307 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 303 /* JSDocTemplateTag */;
+ return node.kind === 308 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 304 /* JSDocTypedefTag */;
+ return node.kind === 309 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */;
+ return node.kind === 310 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 310 /* JSDocPropertyTag */ || node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 292 /* JSDocTypeLiteral */;
+ return node.kind === 297 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
function isJSDocCallbackTag(node) {
- return node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocCallbackTag = isJSDocCallbackTag;
function isJSDocSignature(node) {
- return node.kind === 293 /* JSDocSignature */;
+ return node.kind === 298 /* JSDocSignature */;
}
ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
@@ -13881,7 +14136,7 @@
(function (ts) {
/* @internal */
function isSyntaxList(n) {
- return n.kind === 306 /* SyntaxList */;
+ return n.kind === 311 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
/* @internal */
@@ -14033,11 +14288,11 @@
switch (kind) {
case 155 /* MethodSignature */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 166 /* ConstructorType */:
return true;
default:
@@ -14328,8 +14583,8 @@
case 208 /* SpreadElement */:
case 212 /* AsExpression */:
case 210 /* OmittedExpression */:
- case 309 /* CommaListExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 314 /* CommaListExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -14343,12 +14598,12 @@
ts.isAssertionExpression = isAssertionExpression;
/* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 308 /* PartiallyEmittedExpression */;
+ return node.kind === 313 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
/* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 307 /* NotEmittedStatement */;
+ return node.kind === 312 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
@@ -14459,9 +14714,9 @@
|| kind === 242 /* TypeAliasDeclaration */
|| kind === 150 /* TypeParameter */
|| kind === 237 /* VariableDeclaration */
- || kind === 304 /* JSDocTypedefTag */
- || kind === 297 /* JSDocCallbackTag */
- || kind === 305 /* JSDocPropertyTag */;
+ || kind === 309 /* JSDocTypedefTag */
+ || kind === 302 /* JSDocCallbackTag */
+ || kind === 310 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
return kind === 239 /* FunctionDeclaration */
@@ -14496,14 +14751,14 @@
|| kind === 219 /* VariableStatement */
|| kind === 224 /* WhileStatement */
|| kind === 231 /* WithStatement */
- || kind === 307 /* NotEmittedStatement */
- || kind === 311 /* EndOfDeclarationMarker */
- || kind === 310 /* MergeDeclarationMarker */;
+ || kind === 312 /* NotEmittedStatement */
+ || kind === 316 /* EndOfDeclarationMarker */
+ || kind === 315 /* MergeDeclarationMarker */;
}
/* @internal */
function isDeclaration(node) {
if (node.kind === 150 /* TypeParameter */) {
- return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node);
+ return (node.parent && node.parent.kind !== 308 /* JSDocTemplateTag */) || ts.isInJSFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -14598,18 +14853,18 @@
/** True if node is of some JSDoc syntax kind. */
/* @internal */
function isJSDocNode(node) {
- return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */;
+ return node.kind >= 288 /* FirstJSDocNode */ && node.kind <= 310 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
+ return node.kind === 296 /* 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 >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */;
+ return node.kind >= 299 /* FirstJSDocTagNode */ && node.kind <= 310 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -14926,6 +15181,10 @@
return !!(compilerOptions.declaration || compilerOptions.composite);
}
ts.getEmitDeclarations = getEmitDeclarations;
+ function isIncrementalCompilation(options) {
+ return !!(options.incremental || options.composite);
+ }
+ ts.isIncrementalCompilation = isIncrementalCompilation;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
}
@@ -15613,7 +15872,7 @@
}
ts.getRegexFromPattern = getRegexFromPattern;
/** @param path directory of the tsconfig.json */
- function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) {
+ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
path = ts.normalizePath(path);
currentDirectory = ts.normalizePath(currentDirectory);
var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
@@ -15623,12 +15882,18 @@
// Associate an array of results with each include regex. This keeps results in order of the "include" order.
// If there are no "includes", then just put everything in results[0].
var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
+ var visited = ts.createMap();
+ var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
var basePath = _a[_i];
visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
}
return ts.flatten(results);
function visitDirectory(path, absolutePath, depth) {
+ var canonicalPath = toCanonical(realpath(absolutePath));
+ if (visited.has(canonicalPath))
+ return;
+ visited.set(canonicalPath, true);
var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
var _loop_1 = function (current) {
var name = combinePaths(path, current);
@@ -16011,6 +16276,19 @@
return arr.slice(index);
}
ts.sliceAfter = sliceAfter;
+ function addRelatedInfo(diagnostic) {
+ var _a;
+ var relatedInformation = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ relatedInformation[_i - 1] = arguments[_i];
+ }
+ if (!diagnostic.relatedInformation) {
+ diagnostic.relatedInformation = [];
+ }
+ (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
+ return diagnostic;
+ }
+ ts.addRelatedInfo = addRelatedInfo;
function minAndMax(arr, getValue) {
Debug.assert(arr.length !== 0);
var min = getValue(arr[0]);
@@ -16210,7 +16488,7 @@
var SourceFileConstructor;
// tslint:enable variable-name
function createNode(kind, pos, end) {
- if (kind === 279 /* SourceFile */) {
+ if (kind === 284 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 72 /* Identifier */) {
@@ -16461,7 +16739,7 @@
case 218 /* Block */:
case 245 /* ModuleBlock */:
return visitNodes(cbNode, cbNodes, node.statements);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return visitNodes(cbNode, cbNodes, node.statements) ||
visitNode(cbNode, node.endOfFileToken);
case 219 /* VariableStatement */:
@@ -16610,7 +16888,7 @@
return visitNode(cbNode, node.expression);
case 258 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
case 260 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
@@ -16639,60 +16917,60 @@
return visitNode(cbNode, node.tagName);
case 171 /* OptionalType */:
case 172 /* RestType */:
- case 283 /* JSDocTypeExpression */:
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 288 /* JSDocOptionalType */:
- case 290 /* JSDocVariadicType */:
+ case 288 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 293 /* JSDocOptionalType */:
+ case 295 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return visitNode(cbNode, node.tagName) ||
(node.isNameFirst
? visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression)
: visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name));
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.constraint) ||
visitNodes(cbNode, cbNodes, node.typeParameters);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return visitNode(cbNode, node.tagName) ||
(node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ node.typeExpression.kind === 288 /* JSDocTypeExpression */
? visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName)
: visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression));
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.typeExpression);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return ts.forEach(node.jsDocPropertyTags, cbNode);
- case 294 /* JSDocTag */:
- case 296 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
return visitNode(cbNode, node.tagName);
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -16772,7 +17050,7 @@
(function (Parser) {
// Share a single scanner across all calls to parse a source file. This helps speed things
// up by avoiding the cost of creating/compiling scanners over and over again.
- var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true);
+ var scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ true);
var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */;
// capture constructors in 'initializeState' to avoid null checks
// tslint:disable variable-name
@@ -17066,7 +17344,7 @@
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(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
+ var sourceFile = new SourceFileConstructor(284 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
@@ -18266,9 +18544,9 @@
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(284 /* JSDocAllType */);
+ var result = createNode(289 /* JSDocAllType */);
if (postFixEquals) {
- return createPostfixType(288 /* JSDocOptionalType */, result);
+ return createPostfixType(293 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -18276,7 +18554,7 @@
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(287 /* JSDocNonNullableType */);
+ var result = createNode(292 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -18300,18 +18578,18 @@
token() === 30 /* GreaterThanToken */ ||
token() === 59 /* EqualsToken */ ||
token() === 50 /* BarToken */) {
- var result = createNode(285 /* JSDocUnknownType */, pos);
+ var result = createNode(290 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(286 /* JSDocNullableType */, pos);
+ var result = createNode(291 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(289 /* JSDocFunctionType */);
+ var result = createNodeWithJSDoc(294 /* JSDocFunctionType */);
nextToken();
fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
@@ -18335,12 +18613,12 @@
var type = parseTypeOrTypePredicate();
scanner.setInJSDocType(false);
if (dotdotdot) {
- var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos);
+ var variadic = createNode(295 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 59 /* EqualsToken */) {
- return createPostfixType(288 /* JSDocOptionalType */, type);
+ return createPostfixType(293 /* JSDocOptionalType */, type);
}
return type;
}
@@ -18712,7 +18990,7 @@
return finishNode(node);
}
var type = parseType();
- if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) {
+ if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 291 /* JSDocNullableType */ && type.pos === type.type.pos) {
type.kind = 171 /* OptionalType */;
}
return type;
@@ -18850,6 +19128,7 @@
case 135 /* NumberKeyword */:
case 146 /* BigIntKeyword */:
case 123 /* BooleanKeyword */:
+ case 133 /* ReadonlyKeyword */:
case 139 /* SymbolKeyword */:
case 142 /* UniqueKeyword */:
case 106 /* VoidKeyword */:
@@ -18898,14 +19177,14 @@
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 52 /* ExclamationToken */:
- type = createPostfixType(287 /* JSDocNonNullableType */, type);
+ type = createPostfixType(292 /* JSDocNonNullableType */, type);
break;
case 56 /* 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 = createPostfixType(286 /* JSDocNullableType */, type);
+ type = createPostfixType(291 /* JSDocNullableType */, type);
break;
case 22 /* OpenBracketToken */:
parseExpected(22 /* OpenBracketToken */);
@@ -18955,6 +19234,7 @@
switch (operator) {
case 129 /* KeyOfKeyword */:
case 142 /* UniqueKeyword */:
+ case 133 /* ReadonlyKeyword */:
return parseTypeOperator(operator);
case 127 /* InferKeyword */:
return parseInferType();
@@ -20014,7 +20294,8 @@
}
function parseJsxText() {
var node = createNode(11 /* JsxText */);
- node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
+ node.text = scanner.getTokenValue();
+ node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
currentToken = scanner.scanJsxToken();
return finishNode(node);
}
@@ -21829,8 +22110,8 @@
var JSDocParser;
(function (JSDocParser) {
function parseJSDocTypeExpressionForTests(content, start, length) {
- initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
- sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
+ initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ sourceFile = createSourceFile("file.js", 7 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
scanner.setText(content, start, length);
currentToken = scanner.scan();
var jsDocTypeExpression = parseJSDocTypeExpression();
@@ -21841,7 +22122,7 @@
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
// Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(283 /* JSDocTypeExpression */);
+ var result = createNode(288 /* JSDocTypeExpression */);
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -21852,7 +22133,7 @@
}
JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
function parseIsolatedJSDocComment(content, start, length) {
- initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
+ initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion
var jsDoc = parseJSDocCommentWorker(start, length);
var diagnostics = parseDiagnostics;
@@ -22004,7 +22285,7 @@
}
}
function createJSDocComment() {
- var result = createNode(291 /* JSDocComment */, start);
+ var result = createNode(296 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -22171,7 +22452,7 @@
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(start, tagName) {
- var result = createNode(294 /* JSDocTag */, start);
+ var result = createNode(299 /* JSDocTag */, start);
result.tagName = tagName;
return finishNode(result);
}
@@ -22230,8 +22511,8 @@
typeExpression = tryParseTypeExpression();
}
var result = target === 1 /* Property */ ?
- createNode(305 /* JSDocPropertyTag */, start) :
- createNode(299 /* JSDocParameterTag */, start);
+ createNode(310 /* JSDocPropertyTag */, start) :
+ createNode(304 /* JSDocParameterTag */, start);
var comment = parseTagComments(indent + scanner.getStartPos() - start);
var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
if (nestedTypeLiteral) {
@@ -22248,18 +22529,18 @@
}
function parseNestedTypeLiteral(typeExpression, name, target, indent) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(288 /* 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, indent, name); })) {
- if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) {
+ if (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 169 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
@@ -22270,25 +22551,25 @@
}
}
function parseReturnTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 305 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(300 /* JSDocReturnTag */, start);
+ var result = createNode(305 /* JSDocReturnTag */, start);
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 307 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(302 /* JSDocTypeTag */, start);
+ var result = createNode(307 /* JSDocTypeTag */, start);
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(start, tagName) {
- var result = createNode(295 /* JSDocAugmentsTag */, start);
+ var result = createNode(300 /* JSDocAugmentsTag */, start);
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
return finishNode(result);
@@ -22315,19 +22596,19 @@
return node;
}
function parseClassTag(start, tagName) {
- var tag = createNode(296 /* JSDocClassTag */, start);
+ var tag = createNode(301 /* JSDocClassTag */, start);
tag.tagName = tagName;
return finishNode(tag);
}
function parseThisTag(start, tagName) {
- var tag = createNode(301 /* JSDocThisTag */, start);
+ var tag = createNode(306 /* JSDocThisTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
return finishNode(tag);
}
function parseEnumTag(start, tagName) {
- var tag = createNode(298 /* JSDocEnumTag */, start);
+ var tag = createNode(303 /* JSDocEnumTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
@@ -22336,7 +22617,7 @@
function parseTypedefTag(start, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespaceOrAsterisk();
- var typedefTag = createNode(304 /* JSDocTypedefTag */, start);
+ var typedefTag = createNode(309 /* JSDocTypedefTag */, start);
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace();
typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
@@ -22350,9 +22631,9 @@
var childTypeTag = void 0;
while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start);
}
- if (child.kind === 302 /* JSDocTypeTag */) {
+ if (child.kind === 307 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -22398,14 +22679,14 @@
return typeNameOrNamespaceName;
}
function parseCallbackTag(start, tagName, indent) {
- var callbackTag = createNode(297 /* JSDocCallbackTag */, start);
+ var callbackTag = createNode(302 /* JSDocCallbackTag */, start);
callbackTag.tagName = tagName;
callbackTag.fullName = parseJSDocTypeNameWithNamespace();
callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
skipWhitespace();
callbackTag.comment = parseTagComments(indent);
var child;
- var jsdocSignature = createNode(293 /* JSDocSignature */, start);
+ var jsdocSignature = createNode(298 /* JSDocSignature */, start);
jsdocSignature.parameters = [];
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
@@ -22413,7 +22694,7 @@
var returnTag = tryParse(function () {
if (parseOptionalJsdoc(58 /* AtToken */)) {
var tag = parseTag(indent);
- if (tag && tag.kind === 300 /* JSDocReturnTag */) {
+ if (tag && tag.kind === 305 /* JSDocReturnTag */) {
return tag;
}
}
@@ -22458,7 +22739,7 @@
case 58 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target, indent);
- if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) &&
+ if (child && (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) &&
target !== 4 /* CallbackParameter */ &&
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
@@ -22528,7 +22809,7 @@
skipWhitespace();
typeParameters.push(typeParameter);
} while (parseOptionalJsdoc(27 /* CommaToken */));
- var result = createNode(303 /* JSDocTemplateTag */, start);
+ var result = createNode(308 /* JSDocTemplateTag */, start);
result.tagName = tagName;
result.constraint = constraint;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -23306,6 +23587,7 @@
["es2016", "lib.es2016.d.ts"],
["es2017", "lib.es2017.d.ts"],
["es2018", "lib.es2018.d.ts"],
+ ["es2019", "lib.es2019.d.ts"],
["esnext", "lib.esnext.d.ts"],
// Host only
["dom", "lib.dom.d.ts"],
@@ -23329,12 +23611,16 @@
["es2017.string", "lib.es2017.string.d.ts"],
["es2017.intl", "lib.es2017.intl.d.ts"],
["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
+ ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
["es2018.intl", "lib.es2018.intl.d.ts"],
["es2018.promise", "lib.es2018.promise.d.ts"],
["es2018.regexp", "lib.es2018.regexp.d.ts"],
- ["esnext.array", "lib.esnext.array.d.ts"],
- ["esnext.symbol", "lib.esnext.symbol.d.ts"],
- ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"],
+ ["es2019.array", "lib.es2019.array.d.ts"],
+ ["es2019.string", "lib.es2019.string.d.ts"],
+ ["es2019.symbol", "lib.es2019.symbol.d.ts"],
+ ["esnext.array", "lib.es2019.array.d.ts"],
+ ["esnext.symbol", "lib.es2019.symbol.d.ts"],
+ ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
["esnext.intl", "lib.esnext.intl.d.ts"],
["esnext.bigint", "lib.esnext.bigint.d.ts"]
];
@@ -23480,14 +23766,15 @@
es2016: 3 /* ES2016 */,
es2017: 4 /* ES2017 */,
es2018: 5 /* ES2018 */,
- esnext: 6 /* ESNext */,
+ es2019: 6 /* ES2019 */,
+ esnext: 7 /* ESNext */,
}),
affectsSourceFile: true,
affectsModuleResolution: true,
paramType: ts.Diagnostics.VERSION,
showInSimplifiedHelpView: true,
category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT,
+ description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT,
},
{
name: "module",
@@ -23609,6 +23896,22 @@
description: ts.Diagnostics.Enable_project_compilation,
},
{
+ name: "incremental",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_incremental_compilation,
+ },
+ {
+ name: "tsBuildInfoFile",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE,
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
+ },
+ {
name: "removeComments",
type: "boolean",
showInSimplifiedHelpView: true,
@@ -25034,7 +25337,7 @@
}
function directoryOfCombinedPath(fileName, basePath) {
// Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
- // until consistient casing errors are reported
+ // until consistent casing errors are reported
return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
}
/**
@@ -27326,7 +27629,7 @@
return "__constructor" /* Constructor */;
case 165 /* FunctionType */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return "__call" /* Call */;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
@@ -27335,7 +27638,7 @@
return "__index" /* Index */;
case 255 /* ExportDeclaration */:
return "__export" /* ExportStar */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// json file should behave as
// module.exports = ...
return "export=" /* ExportEquals */;
@@ -27346,12 +27649,12 @@
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
case 151 /* 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 === 289 /* 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 === 294 /* 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;
@@ -27435,13 +27738,15 @@
message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
messageNeedsName_1 = false;
}
- if (symbol.declarations && symbol.declarations.length) {
+ var multipleDefaultExports_1 = false;
+ if (ts.length(symbol.declarations)) {
// If the current node is a default export of some sort, then check if
// there are any other default exports that we need to error on.
// 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;
+ multipleDefaultExports_1 = true;
}
else {
// This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
@@ -27452,14 +27757,22 @@
(node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) {
message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
messageNeedsName_1 = false;
+ multipleDefaultExports_1 = true;
}
}
}
- 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);
+ var declarationName_1 = ts.getNameOfDeclaration(node) || node;
+ var relatedInformation_1 = [];
+ ts.forEach(symbol.declarations, function (declaration, index) {
+ var decl = ts.getNameOfDeclaration(declaration) || declaration;
+ var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
+ file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo(diag, createDiagnosticForNode(declarationName_1, index === 0 ? ts.Diagnostics.Another_export_default_is_here : ts.Diagnostics.and_here)) : diag);
+ if (multipleDefaultExports_1) {
+ relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
+ }
+ });
+ var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
+ file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInformation_1)) : diag);
symbol = createSymbol(0 /* None */, name);
}
}
@@ -27575,7 +27888,7 @@
}
}
// We create a return control flow graph for IIFEs and constructors. For constructors
- // we use the return control flow graph in strict property intialization checks.
+ // we use the return control flow graph in strict property initialization checks.
currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined;
currentBreakTarget = undefined;
currentContinueTarget = undefined;
@@ -27590,7 +27903,7 @@
if (hasExplicitReturn)
node.flags |= 256 /* HasExplicitReturn */;
}
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
node.flags |= emitFlags;
}
if (currentReturnTarget) {
@@ -27734,12 +28047,12 @@
case 191 /* CallExpression */:
bindCallExpressionFlow(node);
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
bindJSDocTypeAlias(node);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
- case 279 /* SourceFile */: {
+ case 284 /* SourceFile */: {
bindEachFunctionsFirst(node.statements);
bind(node.endOfFileToken);
break;
@@ -28426,7 +28739,7 @@
case 243 /* EnumDeclaration */:
case 188 /* ObjectLiteralExpression */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 268 /* JsxAttributes */:
return 1 /* IsContainer */;
case 241 /* InterfaceDeclaration */:
@@ -28435,7 +28748,7 @@
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
return 1 /* IsContainer */ | 32 /* HasLocals */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
case 156 /* MethodDeclaration */:
if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
@@ -28448,8 +28761,8 @@
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
- case 289 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
case 165 /* FunctionType */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
@@ -28503,7 +28816,7 @@
// handlers to take care of declaring these child members.
case 244 /* ModuleDeclaration */:
return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return declareSourceFileMember(node, symbolFlags, symbolExcludes);
case 209 /* ClassExpression */:
case 240 /* ClassDeclaration */:
@@ -28511,7 +28824,7 @@
case 243 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 188 /* ObjectLiteralExpression */:
case 241 /* InterfaceDeclaration */:
case 268 /* JsxAttributes */:
@@ -28525,7 +28838,7 @@
case 166 /* ConstructorType */:
case 160 /* CallSignature */:
case 161 /* ConstructSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 162 /* IndexSignature */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
@@ -28535,9 +28848,9 @@
case 239 /* FunctionDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
- case 289 /* JSDocFunctionType */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 294 /* JSDocFunctionType */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
// All the children of these container types are never visible through another
@@ -28560,8 +28873,8 @@
: declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node) {
- var body = node.kind === 279 /* SourceFile */ ? node : node.body;
- if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
+ var body = node.kind === 284 /* SourceFile */ ? node : node.body;
+ if (body && (body.kind === 284 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
var stat = _a[_i];
if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) {
@@ -28695,7 +29008,7 @@
case 244 /* ModuleDeclaration */:
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalOrCommonJsModule(container)) {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
@@ -28833,7 +29146,7 @@
function checkStrictModeFunctionDeclaration(node) {
if (languageVersion < 2 /* ES2015 */) {
// Report error if function is not top level function declaration
- if (blockScopeContainer.kind !== 279 /* SourceFile */ &&
+ if (blockScopeContainer.kind !== 284 /* SourceFile */ &&
blockScopeContainer.kind !== 244 /* ModuleDeclaration */ &&
!ts.isFunctionLike(blockScopeContainer)) {
// We check first if the name is inside class declaration or class expression; if so give explicit message
@@ -29108,12 +29421,12 @@
case 159 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */);
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
case 166 /* ConstructorType */:
return bindFunctionOrConstructorType(node);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 181 /* MappedType */:
return bindAnonymousTypeWorker(node);
case 188 /* ObjectLiteralExpression */:
@@ -29172,7 +29485,7 @@
return bindExportDeclaration(node);
case 254 /* ExportAssignment */:
return bindExportAssignment(node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
updateStrictModeStatementList(node.statements);
return bindSourceFileIfExternalModule();
case 218 /* Block */:
@@ -29182,22 +29495,22 @@
// falls through
case 245 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
- case 299 /* JSDocParameterTag */:
- if (node.parent.kind === 293 /* JSDocSignature */) {
+ case 304 /* JSDocParameterTag */:
+ if (node.parent.kind === 298 /* JSDocSignature */) {
return bindParameter(node);
}
- if (node.parent.kind !== 292 /* JSDocTypeLiteral */) {
+ if (node.parent.kind !== 297 /* JSDocTypeLiteral */) {
break;
}
// falls through
- case 305 /* JSDocPropertyTag */:
+ case 310 /* JSDocPropertyTag */:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 293 /* JSDocOptionalType */ ?
4 /* Property */ | 16777216 /* Optional */ :
4 /* Property */;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
}
}
@@ -29369,9 +29682,14 @@
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 279 /* SourceFile */:
- // this.foo assignment in a source file
- // Do not bind. It would be nice to support this someday though.
+ case 284 /* SourceFile */:
+ // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
+ if (thisContainer.commonJsModuleIndicator) {
+ declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
+ }
+ else {
+ declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220414 /* FunctionScopedVariableExcludes */);
+ }
break;
default:
ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer));
@@ -29381,7 +29699,7 @@
if (node.expression.kind === 100 /* ThisKeyword */) {
bindThisPropertyAssignment(node);
}
- else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) {
+ else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 284 /* SourceFile */) {
if (ts.isPrototypeAccess(node.expression)) {
bindPrototypePropertyAssignment(node, node.parent);
}
@@ -29418,7 +29736,7 @@
}
function bindObjectDefinePropertyAssignment(node) {
var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
- var isToplevel = node.parent.parent.kind === 279 /* SourceFile */;
+ var isToplevel = node.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false);
bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
}
@@ -29485,8 +29803,8 @@
function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
var namespaceSymbol = lookupSymbolForPropertyAccess(name);
var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
- ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */
- : propertyAccess.parent.parent.kind === 279 /* SourceFile */;
+ ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 284 /* SourceFile */
+ : propertyAccess.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty);
bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
}
@@ -29624,7 +29942,7 @@
}
}
function bindParameter(node) {
- if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) {
+ if (node.kind === 304 /* JSDocParameterTag */ && container.kind !== 298 /* JSDocSignature */) {
return;
}
if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) {
@@ -29882,44 +30200,37 @@
ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
function computeCallExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
+ var callee = ts.skipOuterExpressions(node.expression);
var expression = node.expression;
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */
- || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) {
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) {
// If the this node contains a SpreadExpression, or is a super call, then it is an ES6
// node.
- transformFlags |= 192 /* AssertES2015 */;
- // super property or element accesses could be inside lambdas, etc, and need a captured `this`,
- // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor)
- if (expression.transformFlags & 67108864 /* ContainsSuper */) {
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 128 /* AssertES2015 */;
+ if (ts.isSuperProperty(callee)) {
+ transformFlags |= 2048 /* ContainsLexicalThis */;
}
}
if (expression.kind === 92 /* ImportKeyword */) {
- transformFlags |= 16777216 /* ContainsDynamicImport */;
- // A dynamic 'import()' call that contains a lexical 'this' will
- // require a captured 'this' when emitting down-level.
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- transformFlags |= 16384 /* ContainsCapturedLexicalThis */;
- }
+ transformFlags |= 524288 /* ContainsDynamicImport */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */;
}
function computeNewExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */) {
// If the this node contains a SpreadElementExpression then it is an ES6
// node.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */;
}
function computeBinaryExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -29927,20 +30238,20 @@
var leftKind = node.left.kind;
if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) {
// Destructuring object assignments with are ES2015 syntax
- // and possibly ESNext if they contain rest
- transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
+ // and possibly ES2018 if they contain rest
+ transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */;
}
else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) {
// Destructuring assignments are ES2015 syntax.
- transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
+ transformFlags |= 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */;
}
else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */
|| operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) {
// Exponentiation is ES2016 syntax.
- transformFlags |= 32 /* AssertES2016 */;
+ transformFlags |= 64 /* AssertES2016 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeParameter(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -29951,147 +30262,131 @@
// syntax.
if (node.questionToken
|| node.type
- || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
+ || (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
|| ts.isThisIdentifier(name)) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// If a parameter has an accessibility modifier, then it is TypeScript syntax.
if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
- transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */;
}
- // parameters with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // parameters with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a parameter has an initializer, a binding pattern or a dotDotDot token, then
// it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
- if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
- transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */;
+ if (subtreeFlags & 65536 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* ParameterExcludes */;
+ return transformFlags & ~536870912 /* ParameterExcludes */;
}
function computeParenthesizedExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
var expression = node.expression;
var expressionKind = expression.kind;
- var expressionTransformFlags = expression.transformFlags;
// 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 === 212 /* AsExpression */
|| expressionKind === 194 /* TypeAssertionExpression */) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- // If the expression of a ParenthesizedExpression is a destructuring assignment,
- // then the ParenthesizedExpression is a destructuring assignment.
- if (expressionTransformFlags & 1024 /* DestructuringAssignment */) {
- transformFlags |= 1024 /* DestructuringAssignment */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~536872257 /* OuterExpressionExcludes */;
+ return transformFlags & ~536870912 /* OuterExpressionExcludes */;
}
function computeClassDeclaration(node, subtreeFlags) {
var transformFlags;
if (ts.hasModifier(node, 2 /* Ambient */)) {
// An ambient declaration is TypeScript syntax.
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
// A ClassDeclaration is ES6 syntax.
- transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// A class with a parameter property assignment, property initializer, computed property name, or decorator is
// TypeScript syntax.
// An exported declaration may be TypeScript syntax, but is handled by the visitor
// for a namespace declaration.
- if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */)
+ if ((subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */)
|| node.typeParameters) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~638121281 /* ClassExcludes */;
+ return transformFlags & ~536888320 /* ClassExcludes */;
}
function computeClassExpression(node, subtreeFlags) {
// A ClassExpression is ES6 syntax.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// A class with a parameter property assignment, property initializer, or decorator is
// TypeScript syntax.
- if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */
+ if (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */
|| node.typeParameters) {
- transformFlags |= 3 /* AssertTypeScript */;
- }
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~638121281 /* ClassExcludes */;
+ return transformFlags & ~536888320 /* ClassExcludes */;
}
function computeHeritageClause(node, subtreeFlags) {
var transformFlags = subtreeFlags;
switch (node.token) {
case 86 /* ExtendsKeyword */:
// An `extends` HeritageClause is ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 109 /* ImplementsKeyword */:
// An `implements` HeritageClause is TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
break;
default:
ts.Debug.fail("Unexpected token for heritage clause");
break;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeCatchClause(node, subtreeFlags) {
var transformFlags = subtreeFlags;
if (!node.variableDeclaration) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 8 /* AssertES2019 */;
}
else if (ts.isBindingPattern(node.variableDeclaration.name)) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637797697 /* CatchClauseExcludes */;
+ return transformFlags & ~536879104 /* CatchClauseExcludes */;
}
function computeExpressionWithTypeArguments(node, subtreeFlags) {
// An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
// extends clause of a class.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// If an ExpressionWithTypeArguments contains type arguments, then it
// is TypeScript syntax.
if (node.typeArguments) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeConstructor(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// TypeScript-specific modifiers and overloads are TypeScript syntax
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* ConstructorExcludes */;
+ return transformFlags & ~537372672 /* ConstructorExcludes */;
}
function computeMethod(node, subtreeFlags) {
// A MethodDeclaration is ES6 syntax.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
// overloads are TypeScript syntax.
if (node.decorators
@@ -30100,21 +30395,21 @@
|| node.type
|| (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// An async method declaration is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* MethodOrAccessorExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */);
}
function computeAccessor(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -30125,25 +30420,25 @@
|| node.type
|| (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly
|| !node.body) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653616449 /* MethodOrAccessorExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */);
}
function computePropertyDeclaration(node, subtreeFlags) {
// A PropertyDeclaration is TypeScript syntax.
- var transformFlags = subtreeFlags | 3 /* AssertTypeScript */;
+ var transformFlags = subtreeFlags | 1 /* AssertTypeScript */;
// If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor
// so that it handle the transformation.
if (node.initializer || ts.isComputedPropertyName(node.name)) {
- transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1024 /* ContainsTypeScriptClassSyntax */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return propagatePropertyNameFlags(node.name, transformFlags & ~536872960 /* PropertyExcludes */);
}
function computeFunctionDeclaration(node, subtreeFlags) {
var transformFlags;
@@ -30152,42 +30447,36 @@
if (!body || (modifierFlags & 2 /* Ambient */)) {
// An ambient declaration is TypeScript syntax.
// A FunctionDeclaration without a body is an overload and is TypeScript syntax.
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
- transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */;
+ transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */;
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (modifierFlags & 2270 /* TypeScriptModifier */
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async function declaration is ES2017 syntax.
if (modifierFlags & 256 /* Async */) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
- // function declarations with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If a FunctionDeclaration's subtree has marked the container as needing to capture the
- // lexical this, or the function contains parameters with initializers, then this node is
- // ES6 syntax.
- if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) {
- transformFlags |= 192 /* AssertES2015 */;
+ // function declarations with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a FunctionDeclaration is generator function and is the body of a
// transformed async function, then this node can be transformed to a
// down-level generator.
- // Currently we do not support transforming any other generator fucntions
+ // Currently we do not support transforming any other generator functions
// down level.
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653620545 /* FunctionExcludes */;
+ return transformFlags & ~537373696 /* FunctionExcludes */;
}
function computeFunctionExpression(node, subtreeFlags) {
var transformFlags = subtreeFlags;
@@ -30196,181 +30485,161 @@
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async function expression is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */;
}
- // function expressions with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If a FunctionExpression's subtree has marked the container as needing to capture the
- // lexical this, or the function contains parameters with initializers, then this node is
- // ES6 syntax.
- if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) {
- transformFlags |= 192 /* AssertES2015 */;
+ // function expressions with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// If a FunctionExpression is generator function and is the body of a
// transformed async function, then this node can be transformed to a
// down-level generator.
if (node.asteriskToken) {
- transformFlags |= 768 /* AssertGenerator */;
+ transformFlags |= 256 /* AssertGenerator */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653620545 /* FunctionExcludes */;
+ return transformFlags & ~537373696 /* FunctionExcludes */;
}
function computeArrowFunction(node, subtreeFlags) {
// An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
- var transformFlags = subtreeFlags | 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 128 /* AssertES2015 */;
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
|| node.typeParameters
|| node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
// An async arrow function is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= 16 /* AssertES2017 */;
+ transformFlags |= 32 /* AssertES2017 */;
}
- // arrow functions with object rest destructuring are ES Next syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
- }
- // If an ArrowFunction contains a lexical this, its container must capture the lexical this.
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- transformFlags |= 16384 /* ContainsCapturedLexicalThis */;
+ // arrow functions with object rest destructuring are ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~653604161 /* ArrowFunctionExcludes */;
+ return transformFlags & ~537371648 /* ArrowFunctionExcludes */;
}
function computePropertyAccess(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// If a PropertyAccessExpression starts with a super keyword, then it is
// ES6 syntax, and requires a lexical `this` binding.
- if (transformFlags & 33554432 /* Super */) {
- transformFlags ^= 33554432 /* Super */;
+ if (node.expression.kind === 98 /* SuperKeyword */) {
// super inside of an async function requires hoisting the super access (ES2017).
- // same for super inside of an async generator, which is ESNext.
- transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */;
+ // same for super inside of an async generator, which is ES2018.
+ transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~570426689 /* PropertyAccessExcludes */;
+ return transformFlags & ~536870912 /* PropertyAccessExcludes */;
}
function computeElementAccess(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- var expression = node.expression;
- var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing
// If an ElementAccessExpression starts with a super keyword, then it is
// ES6 syntax, and requires a lexical `this` binding.
- if (expressionFlags & 33554432 /* Super */) {
- transformFlags &= ~33554432 /* Super */;
+ if (node.expression.kind === 98 /* SuperKeyword */) {
// super inside of an async function requires hoisting the super access (ES2017).
- // same for super inside of an async generator, which is ESNext.
- transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */;
+ // same for super inside of an async generator, which is ES2018.
+ transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~570426689 /* PropertyAccessExcludes */;
+ return transformFlags & ~536870912 /* PropertyAccessExcludes */;
}
function computeVariableDeclaration(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- // A VariableDeclaration containing ObjectRest is ESNext syntax
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally?
+ // A VariableDeclaration containing ObjectRest is ES2018 syntax
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */;
}
// Type annotations are TypeScript syntax.
if (node.type) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeVariableStatement(node, subtreeFlags) {
var transformFlags;
var declarationListTransformFlags = node.declarationList.transformFlags;
// An ambient declaration is TypeScript syntax.
if (ts.hasModifier(node, 2 /* Ambient */)) {
- transformFlags = 3 /* AssertTypeScript */;
+ transformFlags = 1 /* AssertTypeScript */;
}
else {
transformFlags = subtreeFlags;
- if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) {
- transformFlags |= 192 /* AssertES2015 */;
+ if (declarationListTransformFlags & 65536 /* ContainsBindingPattern */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeLabeledStatement(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
- if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */
+ if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */
&& ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeImportEquals(node, subtreeFlags) {
var transformFlags = subtreeFlags;
// An ImportEqualsDeclaration with a namespace reference is TypeScript.
if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeExpressionStatement(node, subtreeFlags) {
var transformFlags = subtreeFlags;
- // If the expression of an expression statement is a destructuring assignment,
- // then we treat the statement as ES6 so that we can indicate that we do not
- // need to hold on to the right-hand side.
- if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) {
- transformFlags |= 192 /* AssertES2015 */;
- }
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~637535553 /* NodeExcludes */;
+ return transformFlags & ~536870912 /* NodeExcludes */;
}
function computeModuleDeclaration(node, subtreeFlags) {
- var transformFlags = 3 /* AssertTypeScript */;
+ var transformFlags = 1 /* AssertTypeScript */;
var modifierFlags = ts.getModifierFlags(node);
if ((modifierFlags & 2 /* Ambient */) === 0) {
transformFlags |= subtreeFlags;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~647001409 /* ModuleExcludes */;
+ return transformFlags & ~537168896 /* ModuleExcludes */;
}
function computeVariableDeclarationList(node, subtreeFlags) {
- var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */;
- if (subtreeFlags & 2097152 /* ContainsBindingPattern */) {
- transformFlags |= 192 /* AssertES2015 */;
+ var transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */;
+ if (subtreeFlags & 65536 /* ContainsBindingPattern */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
// If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
if (node.flags & 3 /* BlockScoped */) {
- transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */;
+ transformFlags |= 128 /* AssertES2015 */ | 32768 /* ContainsBlockScopedBinding */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
- return transformFlags & ~639894849 /* VariableDeclarationListExcludes */;
+ return transformFlags & ~536944640 /* VariableDeclarationListExcludes */;
}
function computeOther(node, kind, subtreeFlags) {
// Mark transformations needed for each node
var transformFlags = subtreeFlags;
- var excludeFlags = 637535553 /* NodeExcludes */;
+ var excludeFlags = 536870912 /* NodeExcludes */;
switch (kind) {
case 121 /* AsyncKeyword */:
case 201 /* AwaitExpression */:
- // async/await is ES2017 syntax, but may be ESNext syntax (for async generators)
- transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */;
+ // async/await is ES2017 syntax, but may be ES2018 syntax (for async generators)
+ transformFlags |= 16 /* AssertES2018 */ | 32 /* AssertES2017 */;
break;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
// These nodes are TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
- excludeFlags = 536872257 /* OuterExpressionExcludes */;
+ transformFlags |= 1 /* AssertTypeScript */;
+ excludeFlags = 536870912 /* OuterExpressionExcludes */;
break;
case 115 /* PublicKeyword */:
case 113 /* PrivateKeyword */:
@@ -30383,7 +30652,7 @@
case 213 /* NonNullExpression */:
case 133 /* ReadonlyKeyword */:
// These nodes are TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */;
+ transformFlags |= 1 /* AssertTypeScript */;
break;
case 260 /* JsxElement */:
case 261 /* JsxSelfClosingElement */:
@@ -30398,7 +30667,7 @@
case 269 /* JsxSpreadAttribute */:
case 270 /* JsxExpression */:
// These nodes are Jsx syntax.
- transformFlags |= 4 /* AssertJsx */;
+ transformFlags |= 2 /* AssertJsx */;
break;
case 14 /* NoSubstitutionTemplateLiteral */:
case 15 /* TemplateHead */:
@@ -30410,32 +30679,32 @@
case 116 /* StaticKeyword */:
case 214 /* MetaProperty */:
// These nodes are ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 10 /* StringLiteral */:
if (node.hasExtendedUnicodeEscape) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
case 8 /* NumericLiteral */:
if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
case 9 /* BigIntLiteral */:
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 4 /* AssertESNext */;
break;
case 227 /* ForOfStatement */:
// This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
if (node.awaitModifier) {
- transformFlags |= 8 /* AssertESNext */;
+ transformFlags |= 16 /* AssertES2018 */;
}
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
break;
case 207 /* YieldExpression */:
// This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
// generator).
- transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */;
+ transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 131072 /* ContainsYield */;
break;
case 120 /* AnyKeyword */:
case 135 /* NumberKeyword */:
@@ -30476,115 +30745,93 @@
case 182 /* LiteralType */:
case 247 /* NamespaceExportDeclaration */:
// Types and signatures are TypeScript syntax, and exclude all other facts.
- transformFlags = 3 /* AssertTypeScript */;
- excludeFlags = -3 /* TypeExcludes */;
+ transformFlags = 1 /* AssertTypeScript */;
+ excludeFlags = -2 /* TypeExcludes */;
break;
case 149 /* ComputedPropertyName */:
// Even though computed property names are ES6, we don't treat them as such.
// This is so that they can flow through PropertyName transforms unaffected.
// Instead, we mark the container as ES6, so that it can properly handle the transform.
- transformFlags |= 524288 /* ContainsComputedPropertyName */;
- if (subtreeFlags & 8192 /* ContainsLexicalThis */) {
- // A computed method name like `[this.getName()](x: string) { ... }` needs to
- // distinguish itself from the normal case of a method body containing `this`:
- // `this` inside a method doesn't need to be rewritten (the method provides `this`),
- // whereas `this` inside a computed name *might* need to be rewritten if the class/object
- // is inside an arrow function:
- // `_this = this; () => class K { [_this.getName()]() { ... } }`
- // To make this distinction, use ContainsLexicalThisInComputedPropertyName
- // instead of ContainsLexicalThis for computed property names
- transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */;
- }
+ transformFlags |= 16384 /* ContainsComputedPropertyName */;
break;
case 208 /* SpreadElement */:
- transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */;
+ transformFlags |= 128 /* AssertES2015 */ | 4096 /* ContainsRestOrSpread */;
break;
case 277 /* SpreadAssignment */:
- transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */;
+ transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */;
break;
case 98 /* SuperKeyword */:
// This node is ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */;
- excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super`
+ transformFlags |= 128 /* AssertES2015 */;
+ excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super`
break;
case 100 /* ThisKeyword */:
// Mark this node and its ancestors as containing a lexical `this` keyword.
- transformFlags |= 8192 /* ContainsLexicalThis */;
+ transformFlags |= 2048 /* ContainsLexicalThis */;
break;
case 184 /* ObjectBindingPattern */:
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
- transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */;
+ if (subtreeFlags & 4096 /* ContainsRestOrSpread */) {
+ transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */;
}
- excludeFlags = 637666625 /* BindingPatternExcludes */;
+ excludeFlags = 536875008 /* BindingPatternExcludes */;
break;
case 185 /* ArrayBindingPattern */:
- transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */;
- excludeFlags = 637666625 /* BindingPatternExcludes */;
+ transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */;
+ excludeFlags = 536875008 /* BindingPatternExcludes */;
break;
case 186 /* BindingElement */:
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
if (node.dotDotDotToken) {
- transformFlags |= 131072 /* ContainsRestOrSpread */;
+ transformFlags |= 4096 /* ContainsRestOrSpread */;
}
break;
case 152 /* Decorator */:
// This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
- transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */;
+ transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */;
break;
case 188 /* ObjectLiteralExpression */:
- excludeFlags = 638358849 /* ObjectLiteralExcludes */;
- if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) {
+ excludeFlags = 536896512 /* ObjectLiteralExcludes */;
+ if (subtreeFlags & 16384 /* ContainsComputedPropertyName */) {
// If an ObjectLiteralExpression contains a ComputedPropertyName, then it
// is an ES6 node.
- transformFlags |= 192 /* AssertES2015 */;
+ transformFlags |= 128 /* AssertES2015 */;
}
- if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) {
- // A computed property name containing `this` might need to be rewritten,
- // so propagate the ContainsLexicalThis flag upward.
- transformFlags |= 8192 /* ContainsLexicalThis */;
- }
- if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) {
// If an ObjectLiteralExpression contains a spread element, then it
- // is an ES next node.
- transformFlags |= 8 /* AssertESNext */;
+ // is an ES2018 node.
+ transformFlags |= 16 /* AssertES2018 */;
}
break;
case 187 /* ArrayLiteralExpression */:
- case 192 /* NewExpression */:
- excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */;
- if (subtreeFlags & 131072 /* ContainsRestOrSpread */) {
- // If the this node contains a SpreadExpression, then it is an ES6
- // node.
- transformFlags |= 192 /* AssertES2015 */;
- }
+ excludeFlags = 536875008 /* ArrayLiteralOrCallOrNewExcludes */;
break;
case 223 /* DoStatement */:
case 224 /* WhileStatement */:
case 225 /* ForStatement */:
case 226 /* ForInStatement */:
// A loop containing a block scoped binding *may* need to be transformed from ES6.
- if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) {
- transformFlags |= 192 /* AssertES2015 */;
+ if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */) {
+ transformFlags |= 128 /* AssertES2015 */;
}
break;
- case 279 /* SourceFile */:
- if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) {
- transformFlags |= 192 /* AssertES2015 */;
- }
+ case 284 /* SourceFile */:
break;
case 230 /* ReturnStatement */:
- // Return statements may require an `await` in ESNext.
- transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */;
+ // Return statements may require an `await` in ES2018.
+ transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */ | 16 /* AssertES2018 */;
break;
case 228 /* ContinueStatement */:
case 229 /* BreakStatement */:
- transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */;
+ transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */;
break;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
return transformFlags & ~excludeFlags;
}
+ function propagatePropertyNameFlags(node, transformFlags) {
+ return transformFlags | (node.transformFlags & 2048 /* PropertyNamePropagatingFlags */);
+ }
/**
* Gets the transform flags to exclude when unioning the transform flags of a subtree.
*
@@ -30594,33 +30841,33 @@
*/
function getTransformFlagsSubtreeExclusions(kind) {
if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) {
- return -3 /* TypeExcludes */;
+ return -2 /* TypeExcludes */;
}
switch (kind) {
case 191 /* CallExpression */:
case 192 /* NewExpression */:
case 187 /* ArrayLiteralExpression */:
- return 637666625 /* ArrayLiteralOrCallOrNewExcludes */;
+ return 536875008 /* ArrayLiteralOrCallOrNewExcludes */;
case 244 /* ModuleDeclaration */:
- return 647001409 /* ModuleExcludes */;
+ return 537168896 /* ModuleExcludes */;
case 151 /* Parameter */:
- return 637535553 /* ParameterExcludes */;
+ return 536870912 /* ParameterExcludes */;
case 197 /* ArrowFunction */:
- return 653604161 /* ArrowFunctionExcludes */;
+ return 537371648 /* ArrowFunctionExcludes */;
case 196 /* FunctionExpression */:
case 239 /* FunctionDeclaration */:
- return 653620545 /* FunctionExcludes */;
+ return 537373696 /* FunctionExcludes */;
case 238 /* VariableDeclarationList */:
- return 639894849 /* VariableDeclarationListExcludes */;
+ return 536944640 /* VariableDeclarationListExcludes */;
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
- return 638121281 /* ClassExcludes */;
+ return 536888320 /* ClassExcludes */;
case 157 /* Constructor */:
- return 653616449 /* ConstructorExcludes */;
+ return 537372672 /* ConstructorExcludes */;
case 156 /* MethodDeclaration */:
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
- return 653616449 /* MethodOrAccessorExcludes */;
+ return 537372672 /* MethodOrAccessorExcludes */;
case 120 /* AnyKeyword */:
case 135 /* NumberKeyword */:
case 146 /* BigIntKeyword */:
@@ -30638,25 +30885,25 @@
case 162 /* IndexSignature */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- return -3 /* TypeExcludes */;
+ return -2 /* TypeExcludes */;
case 188 /* ObjectLiteralExpression */:
- return 638358849 /* ObjectLiteralExcludes */;
+ return 536896512 /* ObjectLiteralExcludes */;
case 274 /* CatchClause */:
- return 637797697 /* CatchClauseExcludes */;
+ return 536879104 /* CatchClauseExcludes */;
case 184 /* ObjectBindingPattern */:
case 185 /* ArrayBindingPattern */:
- return 637666625 /* BindingPatternExcludes */;
+ return 536875008 /* BindingPatternExcludes */;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
case 195 /* ParenthesizedExpression */:
case 98 /* SuperKeyword */:
- return 536872257 /* OuterExpressionExcludes */;
+ return 536870912 /* OuterExpressionExcludes */;
case 189 /* PropertyAccessExpression */:
case 190 /* ElementAccessExpression */:
- return 570426689 /* PropertyAccessExcludes */;
+ return 536870912 /* PropertyAccessExcludes */;
default:
- return 637535553 /* NodeExcludes */;
+ return 536870912 /* NodeExcludes */;
}
}
ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
@@ -30905,6 +31152,7 @@
var enumCount = 0;
var instantiationDepth = 0;
var constraintDepth = 0;
+ var currentNode;
var emptySymbols = ts.createSymbolTable();
var identityMapper = ts.identity;
var compilerOptions = host.getCompilerOptions();
@@ -30921,8 +31169,14 @@
var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
var emitResolver = createResolver();
var nodeBuilder = createNodeBuilder();
+ var globals = ts.createSymbolTable();
var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
undefinedSymbol.declarations = [];
+ var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
+ globalThisSymbol.exports = globals;
+ globalThisSymbol.valueDeclaration = ts.createNode(72 /* Identifier */);
+ globalThisSymbol.valueDeclaration.escapedText = "globalThis";
+ globals.set(globalThisSymbol.escapedName, globalThisSymbol);
var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
var requireSymbol = createSymbol(4 /* Property */, "require");
/** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
@@ -31052,11 +31306,13 @@
isContextSensitive: isContextSensitive,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 0 /* Normal */);
},
getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */);
},
+ getExpandedParameters: getExpandedParameters,
+ hasEffectiveRestParameter: hasEffectiveRestParameter,
getConstantValue: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
return node ? getConstantValue(node) : undefined;
@@ -31118,6 +31374,8 @@
getNeverType: function () { return neverType; },
isSymbolAccessible: isSymbolAccessible,
getObjectFlags: ts.getObjectFlags,
+ isArrayType: isArrayType,
+ isTupleType: isTupleType,
isArrayLikeType: isArrayLikeType,
isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
@@ -31133,9 +31391,9 @@
getAccessibleSymbolChain: getAccessibleSymbolChain,
getTypePredicateOfSignature: getTypePredicateOfSignature,
resolveExternalModuleSymbol: resolveExternalModuleSymbol,
- tryGetThisTypeAt: function (node) {
+ tryGetThisTypeAt: function (node, includeGlobalThis) {
node = ts.getParseTreeNode(node);
- return node && tryGetThisTypeAt(node);
+ return node && tryGetThisTypeAt(node, includeGlobalThis);
},
getTypeArgumentConstraint: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
@@ -31182,10 +31440,10 @@
},
getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
};
- function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) {
+ function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
apparentArgumentCount = argumentCount;
- var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined;
+ var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
apparentArgumentCount = undefined;
return res;
}
@@ -31194,6 +31452,7 @@
var intersectionTypes = ts.createMap();
var literalTypes = ts.createMap();
var indexedAccessTypes = ts.createMap();
+ var conditionalTypes = ts.createMap();
var evolvingArrayTypes = [];
var undefinedProperties = ts.createMap();
var unknownSymbol = createSymbol(4 /* Property */, "unknown");
@@ -31204,9 +31463,9 @@
var errorType = createIntrinsicType(1 /* Any */, "error");
var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
- var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined");
+ var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */);
var nullType = createIntrinsicType(65536 /* Null */, "null");
- var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null");
+ var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */);
var stringType = createIntrinsicType(4 /* String */, "string");
var numberType = createIntrinsicType(8 /* Number */, "number");
var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
@@ -31232,6 +31491,7 @@
var voidType = createIntrinsicType(16384 /* Void */, "void");
var neverType = createIntrinsicType(131072 /* Never */, "never");
var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
+ var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */);
var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
@@ -31248,7 +31508,7 @@
var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
// The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
// in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
- anyFunctionType.flags |= 536870912 /* ContainsAnyFunctionType */;
+ anyFunctionType.objectFlags |= 524288 /* NonInferrableType */;
var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
@@ -31262,7 +31522,6 @@
var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
- var globals = ts.createSymbolTable();
/** Key is "/path/to/a.ts|/path/to/b.ts". */
var amalgamatedDuplicates;
var reverseMappedCache = ts.createMap();
@@ -31461,9 +31720,11 @@
var CheckMode;
(function (CheckMode) {
CheckMode[CheckMode["Normal"] = 0] = "Normal";
- CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive";
+ CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
- CheckMode[CheckMode["Contextual"] = 3] = "Contextual";
+ CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
+ CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
+ CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
})(CheckMode || (CheckMode = {}));
var CallbackCheck;
(function (CallbackCheck) {
@@ -31550,18 +31811,6 @@
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)
@@ -31741,7 +31990,7 @@
err.relatedInformation = err.relatedInformation || [];
if (ts.length(err.relatedInformation) >= 5)
continue;
- addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here));
+ ts.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) {
@@ -31819,7 +32068,7 @@
return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
}
function isGlobalSourceFile(node) {
- return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
+ return node.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning) {
@@ -31993,7 +32242,7 @@
// - 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 & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) {
+ if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 296 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -32035,14 +32284,14 @@
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
isInExternalModule = true;
// falls through
case 244 /* ModuleDeclaration */:
var moduleExports = getSymbolOfNode(location).exports;
- if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) {
+ if (location.kind === 284 /* 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 */)) {
@@ -32210,12 +32459,18 @@
// @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
// }
//
- if (location.parent && ts.isClassElement(location.parent)) {
+ // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
+ //
+ // type T = number;
+ // declare function y(x: T): any;
+ // @param(1 as T) // <-- T should resolve to the type alias outside of class C
+ // class C<T> {}
+ if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 240 /* ClassDeclaration */)) {
location = location.parent;
}
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
// js type aliases do not resolve names from their host, so skip past it
location = ts.getJSDocHost(location);
break;
@@ -32234,7 +32489,7 @@
}
if (!result) {
if (lastLocation) {
- ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */);
+ ts.Debug.assert(lastLocation.kind === 284 /* SourceFile */);
if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
return lastLocation.symbol;
}
@@ -32257,7 +32512,8 @@
!checkAndReportErrorForExtendingInterface(errorLocation) &&
!checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
!checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
- !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) {
+ !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
+ !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
var suggestion = void 0;
if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
@@ -32265,7 +32521,7 @@
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));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
}
}
}
@@ -32422,6 +32678,16 @@
}
return false;
}
+ function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
+ if (meaning & (67897832 /* Type */ & ~1920 /* Namespace */)) {
+ var symbol = resolveSymbol(resolveName(errorLocation, name, ~67897832 /* Type */ & 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
+ error(errorLocation, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here, ts.unescapeLeadingUnderscores(name));
+ return true;
+ }
+ }
+ return false;
+ }
function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) {
if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") {
@@ -32430,7 +32696,7 @@
}
var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
- var message = (name === "Promise" || name === "Symbol")
+ var message = isES2015OrLaterConstructorName(name)
? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later
: ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
@@ -32439,6 +32705,18 @@
}
return false;
}
+ function isES2015OrLaterConstructorName(n) {
+ switch (n) {
+ case "Promise":
+ case "Symbol":
+ case "Map":
+ case "WeakMap":
+ case "Set":
+ case "WeakSet":
+ return true;
+ }
+ return false;
+ }
function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) {
var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
@@ -32481,7 +32759,7 @@
}
}
if (diagnosticMessage) {
- addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
+ ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
}
}
}
@@ -32665,7 +32943,7 @@
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));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
}
}
else {
@@ -32985,22 +33263,14 @@
return undefined;
}
if (moduleNotFoundError) {
- // For relative paths, see if this was possibly a projectReference redirect
- if (ts.pathIsRelative(moduleReference)) {
- var sourceFile_1 = ts.getSourceFileOfNode(location);
- var redirects = sourceFile_1.redirectedReferences;
- if (redirects) {
- var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName));
- for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) {
- var ext = _a[_i];
- var probePath = normalizedTargetPath + ext;
- if (redirects.indexOf(probePath) >= 0) {
- error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath);
+ // See if this was possibly a projectReference redirect
+ if (resolvedModule) {
+ var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
+ if (redirect) {
+ error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
return undefined;
}
}
- }
- }
if (resolutionDiagnostic) {
error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
}
@@ -33067,7 +33337,7 @@
function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) {
var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
if (!dontResolveAlias && symbol) {
- if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) {
+ if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 284 /* SourceFile */)) {
var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
? "allowSyntheticDefaultImports"
: "esModuleInterop";
@@ -33340,9 +33610,11 @@
result.id = typeCount;
return result;
}
- function createIntrinsicType(kind, intrinsicName) {
+ function createIntrinsicType(kind, intrinsicName, objectFlags) {
+ if (objectFlags === void 0) { objectFlags = 0; }
var type = createType(kind);
type.intrinsicName = intrinsicName;
+ type.objectFlags = objectFlags;
return type;
}
function createBooleanType(trueFalseTypes) {
@@ -33413,7 +33685,7 @@
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
@@ -33653,10 +33925,10 @@
return node && getSymbolOfNode(node);
}
function hasExternalModuleSymbol(declaration) {
- return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isAmbientModule(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
- return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
var aliasesToMakeVisible;
@@ -34025,8 +34297,8 @@
context.inferTypeParameters = type.root.inferTypeParameters;
var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
context.inferTypeParameters = saveInferTypeParameters;
- var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context);
- var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context);
+ var trueTypeNode = typeToTypeNodeHelper(type.trueType, context);
+ var falseTypeNode = typeToTypeNodeHelper(type.falseType, context);
context.approximateLength += 15;
return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
}
@@ -34113,7 +34385,7 @@
var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
(symbol.parent || // is exported function symbol
ts.forEach(symbol.declarations, function (declaration) {
- return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
+ return declaration.parent.kind === 284 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
// typeof is allowed only for static/non local functions
@@ -34153,13 +34425,14 @@
}
function typeReferenceToTypeNode(type) {
var typeArguments = type.typeArguments || ts.emptyArray;
- if (type.target === globalArrayType) {
+ if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
if (context.flags & 2 /* WriteArrayAsGenericType */) {
var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
- return ts.createTypeReferenceNode("Array", [typeArgumentNode]);
+ return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
}
var elementType = typeToTypeNodeHelper(typeArguments[0], context);
- return ts.createArrayTypeNode(elementType);
+ var arrayType = ts.createArrayTypeNode(elementType);
+ return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, arrayType);
}
else if (type.target.objectFlags & 8 /* Tuple */) {
if (typeArguments.length > 0) {
@@ -34172,11 +34445,13 @@
ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
ts.createOptionalTypeNode(tupleConstituentNodes[i]);
}
- return ts.createTupleTypeNode(tupleConstituentNodes);
+ var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes);
+ return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
}
}
if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
- return ts.createTupleTypeNode([]);
+ var tupleTypeNode = ts.createTupleTypeNode([]);
+ return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
}
context.encounteredError = true;
return undefined; // TODO: GH#18217
@@ -34340,7 +34615,7 @@
context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
context.enclosingDeclaration = saveEnclosingDeclaration;
var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined;
- if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) {
+ if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
var signatures = getSignaturesOfType(propertyType, 0 /* Call */);
for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
var signature = signatures_1[_i];
@@ -34476,7 +34751,7 @@
var savedContextFlags = context.flags;
context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
- type.symbol.declarations[0] &&
+ type.symbol.declarations && type.symbol.declarations[0] &&
ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
typeParameterShadowsNameInScope(type, context);
var name = shouldUseGeneratedName
@@ -34495,7 +34770,7 @@
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */);
if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
- parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */);
+ parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 304 /* JSDocParameterTag */);
}
var parameterType = getTypeOfSymbol(parameterSymbol);
if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
@@ -34653,7 +34928,7 @@
return top;
}
function getSpecifierForModuleSymbol(symbol, context) {
- var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */);
+ var file = ts.getDeclarationOfKind(symbol, 284 /* SourceFile */);
if (file && file.moduleName !== undefined) {
// Use the amd name if it is available
return file.moduleName;
@@ -34906,7 +35181,7 @@
ts.isExternalModuleAugmentation(node.parent.parent);
}
function isDefaultBindingContext(location) {
- return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location);
+ return location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location);
}
function getNameOfSymbolFromNameType(symbol, context) {
var nameType = symbol.nameType;
@@ -34983,8 +35258,8 @@
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* 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));
@@ -35011,7 +35286,7 @@
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 !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
+ !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 284 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
return isGlobalSourceFile(parent);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
@@ -35053,7 +35328,7 @@
// Type parameters are always visible
case 150 /* TypeParameter */:
// Source file and namespace export are always visible
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 247 /* NamespaceExportDeclaration */:
return true;
// Export assignments do not create name bindings outside the module
@@ -35232,7 +35507,7 @@
if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
&& !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
&& isSpreadableProperty(prop)) {
- members.set(prop.escapedName, getSpreadSymbol(prop));
+ members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
}
}
var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
@@ -35301,17 +35576,8 @@
function getTypeForBindingElement(declaration) {
var pattern = declaration.parent;
var parentType = getTypeForBindingElementParent(pattern.parent);
- // If parent has the unknown (error) type, then so does this binding element
- if (parentType === errorType) {
- return errorType;
- }
- // If no type was specified or inferred for parent,
- // infer from the initializer of the binding element if one is present.
- // Otherwise, go with the undefined type of the parent.
- if (!parentType) {
- return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType;
- }
- if (isTypeAny(parentType)) {
+ // If no type or an any type was inferred for parent, infer that for the binding element
+ if (!parentType || isTypeAny(parentType)) {
return parentType;
}
// Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
@@ -35393,6 +35659,11 @@
if (optional === void 0) { optional = true; }
return strictNullChecks && optional ? getOptionalType(type) : type;
}
+ function isParameterOfContextuallyTypedFunction(node) {
+ return node.kind === 151 /* Parameter */ &&
+ (node.parent.kind === 196 /* FunctionExpression */ || node.parent.kind === 197 /* ArrowFunction */) &&
+ !!getContextualType(node.parent);
+ }
// Return the inferred type for a variable, parameter, or property declaration
function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
// A variable declared in a for..in statement is of type string, or of type keyof T when the
@@ -35468,8 +35739,9 @@
return containerObjectType;
}
}
- // Use the type of the initializer expression if one is present
- if (declaration.initializer) {
+ // Use the type of the initializer expression if one is present and the declaration is
+ // not a parameter of a contextually typed function
+ if (declaration.initializer && !isParameterOfContextuallyTypedFunction(declaration)) {
var type = checkDeclarationInitializer(declaration);
return addOptionality(type, isOptional);
}
@@ -35478,8 +35750,9 @@
// I.e <Elem attr /> is sugar for <Elem attr={true} />
return trueType;
}
- // If the declaration specifies a binding pattern, use the type implied by the binding pattern
- if (ts.isBindingPattern(declaration.name)) {
+ // If the declaration specifies a binding pattern and is not a parameter of a contextually
+ // typed function, use the type implied by the binding pattern
+ if (ts.isBindingPattern(declaration.name) && !isParameterOfContextuallyTypedFunction(declaration)) {
return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
}
// No type specified and nothing can be inferred
@@ -35535,7 +35808,7 @@
definedInConstructor = true;
}
}
- var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217
+ var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
type = getUnionType(sourceTypes, 2 /* Subtype */);
}
var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
@@ -35686,7 +35959,7 @@
function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
var members = ts.createSymbolTable();
var stringIndexInfo;
- var objectFlags = 128 /* ObjectLiteral */;
+ var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
ts.forEach(pattern.elements, function (e) {
var name = e.propertyName || e.name;
if (e.dotDotDotToken) {
@@ -35707,7 +35980,6 @@
members.set(symbol.escapedName, symbol);
});
var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
- result.flags |= 268435456 /* ContainsObjectLiteral */;
result.objectFlags |= objectFlags;
if (includePatternInType) {
result.pattern = pattern;
@@ -35791,7 +36063,16 @@
}
function getTypeOfVariableOrParameterOrProperty(symbol) {
var links = getSymbolLinks(symbol);
- return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol));
+ if (!links.type) {
+ var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
+ // For a contextually typed parameter it is possible that a type has already
+ // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
+ // to preserve this type.
+ if (!links.type) {
+ links.type = type;
+ }
+ }
+ return links.type;
}
function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
// Handle prototype property
@@ -35824,19 +36105,19 @@
}
return type_1;
}
- if (declaration.kind === 254 /* ExportAssignment */) {
- return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
- }
// Handle variable, parameter or property
if (!pushTypeResolution(symbol, 0 /* Type */)) {
// Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
if (symbol.flags & 512 /* ValueModule */) {
return getTypeOfFuncClassEnumModule(symbol);
}
- return errorType;
+ return reportCircularityError(symbol);
}
var type;
- if (ts.isInJSFile(declaration) &&
+ if (declaration.kind === 254 /* ExportAssignment */) {
+ type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
+ }
+ else if (ts.isInJSFile(declaration) &&
(ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) {
type = getWidenedTypeFromAssignmentDeclaration(symbol);
}
@@ -35891,7 +36172,7 @@
if (symbol.flags & 512 /* ValueModule */) {
return getTypeOfFuncClassEnumModule(symbol);
}
- type = reportCircularityError(symbol);
+ return reportCircularityError(symbol);
}
return type;
}
@@ -36069,15 +36350,19 @@
return links.type;
}
function reportCircularityError(symbol) {
+ var declaration = symbol.valueDeclaration;
// Check if variable has type annotation that circularly references the variable itself
- if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) {
+ if (ts.getEffectiveTypeAnnotationNode(declaration)) {
error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
return errorType;
}
- // Otherwise variable has initializer that circularly references the variable itself
- if (noImplicitAny) {
+ // Check if variable has initializer that circularly references the variable itself
+ if (noImplicitAny && (declaration.kind !== 151 /* Parameter */ || declaration.initializer)) {
error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
}
+ // Circularities could also result from parameters in function expressions that end up
+ // having themselves as contextual types following type argument inference. In those cases
+ // we have already reported an implicit any error so we don't report anything here.
return anyType;
}
function getTypeOfSymbol(symbol) {
@@ -36153,15 +36438,15 @@
case 155 /* MethodSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 308 /* JSDocTemplateTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 181 /* MappedType */:
case 175 /* ConditionalType */:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -36282,7 +36567,7 @@
ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
}
}
- addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
+ ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn)));
}
return type.resolvedBaseConstructorType = errorType;
}
@@ -36293,7 +36578,7 @@
function getBaseTypes(type) {
if (!type.resolvedBaseTypes) {
if (type.objectFlags & 8 /* Tuple */) {
- type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))];
+ type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)];
}
else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
if (type.symbol.flags & 32 /* Class */) {
@@ -36658,7 +36943,7 @@
}
return false;
}
- /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */
+ /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
function isThislessTypeParameter(node) {
var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
return !constraint || isThislessType(constraint);
@@ -36701,6 +36986,8 @@
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
case 157 /* Constructor */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
return isThislessFunctionLikeDeclaration(declaration);
}
}
@@ -37032,8 +37319,18 @@
return sig;
}
function cloneSignature(sig) {
- return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
+ var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined,
/*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes);
+ result.target = sig.target;
+ result.mapper = sig.mapper;
+ return result;
+ }
+ function createUnionSignature(signature, unionSignatures) {
+ var result = cloneSignature(signature);
+ result.unionSignatures = unionSignatures;
+ result.target = undefined;
+ result.mapper = undefined;
+ return result;
}
function getExpandedParameters(sig) {
if (sig.hasRestParameter) {
@@ -37142,9 +37439,8 @@
var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */);
thisParameter = createSymbolWithType(signature.thisParameter, thisType);
}
- s = cloneSignature(signature);
+ s = createUnionSignature(signature, unionSignatures);
s.thisParameter = thisParameter;
- s.unionSignatures = unionSignatures;
}
(result || (result = [])).push(s);
}
@@ -37259,13 +37555,22 @@
function unionSpreadIndexInfos(info1, info2) {
return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
}
- function includeMixinType(type, types, index) {
+ function findMixins(types) {
+ var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
+ var mixinFlags = ts.map(types, isMixinConstructorType);
+ if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
+ var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
+ mixinFlags[firstMixinIndex] = false;
+ }
+ return mixinFlags;
+ }
+ function includeMixinType(type, types, mixinFlags, index) {
var mixedTypes = [];
for (var i = 0; i < types.length; i++) {
if (i === index) {
mixedTypes.push(type);
}
- else if (isMixinConstructorType(types[i])) {
+ else if (mixinFlags[i]) {
mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
}
}
@@ -37279,7 +37584,8 @@
var stringIndexInfo;
var numberIndexInfo;
var types = type.types;
- var mixinCount = ts.countWhere(types, isMixinConstructorType);
+ var mixinFlags = findMixins(types);
+ var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
var _loop_6 = function (i) {
var t = type.types[i];
// When an intersection type contains mixin constructor types, the construct signatures from
@@ -37287,12 +37593,12 @@
// other construct signatures in the intersection type. For example, the intersection type
// '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
// 'new(s: string) => A & B'.
- if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) {
+ if (!mixinFlags[i]) {
var signatures = getSignaturesOfType(t, 1 /* Construct */);
if (signatures.length && mixinCount > 0) {
signatures = ts.map(signatures, function (s) {
var clone = cloneSignature(s);
- clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i);
+ clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
return clone;
});
}
@@ -37336,6 +37642,15 @@
var stringIndexInfo = void 0;
if (symbol.exports) {
members = getExportsOfSymbol(symbol);
+ if (symbol === globalThisSymbol) {
+ var varsOnly_1 = ts.createMap();
+ members.forEach(function (p) {
+ if (!(p.flags & 418 /* BlockScoped */)) {
+ varsOnly_1.set(p.escapedName, p);
+ }
+ });
+ members = varsOnly_1;
+ }
}
setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
if (symbol.flags & 32 /* Class */) {
@@ -37635,7 +37950,7 @@
var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
- return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected);
+ return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
});
}
function getAllPossiblePropertiesOfTypes(types) {
@@ -37668,6 +37983,9 @@
return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
}
function getConstraintOfIndexedAccess(type) {
+ return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
+ }
+ function getConstraintFromIndexedAccess(type) {
var objectType = getConstraintOfType(type.objectType) || type.objectType;
if (objectType !== type.objectType) {
var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType);
@@ -37680,13 +37998,13 @@
}
function getDefaultConstraintOfConditionalType(type) {
if (!type.resolvedDefaultConstraint) {
- var rootTrueType = type.root.trueType;
- var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */)
- ? rootTrueType
- : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */
- ? rootTrueType.typeVariable
- : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]);
- type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]);
+ // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
+ // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
+ // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
+ // in effect treating `any` like `never` rather than `unknown` in this location.
+ var trueConstraint = getInferredTrueTypeFromConditionalType(type);
+ var falseConstraint = type.falseType;
+ type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
}
return type.resolvedDefaultConstraint;
}
@@ -37696,7 +38014,13 @@
// with its constraint. We do this because if the constraint is a union type it will be distributed
// over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
// removes 'undefined' from T.
- if (type.root.isDistributive) {
+ // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
+ // as the constraint for all type params (check type included) have been replace with `unknown`, which
+ // is going to produce even more false positive/negative results than the distribute constraint already does.
+ // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
+ // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
+ // likely doesn't need to exist.
+ if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
var simplified = getSimplifiedType(type.checkType);
var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
if (constraint && constraint !== type.checkType) {
@@ -37709,9 +38033,12 @@
}
return undefined;
}
- function getConstraintOfConditionalType(type) {
+ function getConstraintFromConditionalType(type) {
return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
}
+ function getConstraintOfConditionalType(type) {
+ return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
+ }
function getUnionConstraintOfIntersection(type, targetIsUnion) {
var constraints;
var hasDisjointDomainType = false;
@@ -37785,18 +38112,31 @@
if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
return circularConstraintType;
}
- if (constraintDepth === 50) {
+ if (constraintDepth >= 50) {
// We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
// very high likelyhood we're dealing with an infinite generic type that perpetually generates
// new type identities as we descend into it. We stop the recursion here and mark this type
// and the outer types as having circular constraints.
+ error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
nonTerminating = true;
return t.immediateBaseConstraint = noConstraintType;
}
constraintDepth++;
var result = computeBaseConstraint(getSimplifiedType(t));
constraintDepth--;
- if (!popTypeResolution() || nonTerminating) {
+ if (!popTypeResolution()) {
+ if (t.flags & 262144 /* TypeParameter */) {
+ var errorNode = getConstraintDeclaration(t);
+ if (errorNode) {
+ var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
+ if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
+ }
+ }
+ }
+ result = circularConstraintType;
+ }
+ if (nonTerminating) {
result = circularConstraintType;
}
t.immediateBaseConstraint = result || noConstraintType;
@@ -37838,8 +38178,11 @@
return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined;
}
if (t.flags & 16777216 /* Conditional */) {
- var constraint = getConstraintOfConditionalType(t);
- return constraint && getBaseConstraint(constraint);
+ var constraint = getConstraintFromConditionalType(t);
+ constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
+ var result = constraint && getBaseConstraint(constraint);
+ constraintDepth--;
+ return result;
}
if (t.flags & 33554432 /* Substitution */) {
return getBaseConstraint(t.substitute);
@@ -37900,7 +38243,7 @@
var typeVariable = getHomomorphicTypeVariable(type);
if (typeVariable) {
var constraint = getConstraintOfTypeParameter(typeVariable);
- if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) {
+ if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
var mapper = makeUnaryTypeMapper(typeVariable, constraint);
return instantiateType(type, combineTypeMappers(mapper, type.mapper));
}
@@ -37918,7 +38261,7 @@
t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
t.flags & 132 /* StringLike */ ? globalStringType :
t.flags & 296 /* NumberLike */ ? globalNumberType :
- t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) :
+ t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ESNext */) :
t.flags & 528 /* BooleanLike */ ? globalBooleanType :
t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
@@ -37926,7 +38269,7 @@
t;
}
function createUnionOrIntersectionProperty(containingType, name) {
- var props;
+ var propSet = ts.createMap();
var indexTypes;
var isUnion = containingType.flags & 1048576 /* Union */;
var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0;
@@ -37942,7 +38285,10 @@
var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
if (prop && !(modifiers & excludeModifiers)) {
commonFlags &= prop.flags;
- props = ts.appendIfUnique(props, prop);
+ var id = "" + getSymbolId(prop);
+ if (!propSet.has(id)) {
+ propSet.set(id, prop);
+ }
checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
(!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) |
(modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) |
@@ -37964,9 +38310,10 @@
}
}
}
- if (!props) {
+ if (!propSet.size) {
return undefined;
}
+ var props = ts.arrayFrom(propSet.values());
if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) {
return props[0];
}
@@ -38138,10 +38485,10 @@
function isJSDocOptionalParameter(node) {
return ts.isInJSFile(node) && (
// node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
- node.type && node.type.kind === 288 /* JSDocOptionalType */
+ node.type && node.type.kind === 293 /* JSDocOptionalType */
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -38175,7 +38522,7 @@
return false;
}
var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}
function createIdentifierTypePredicate(parameterName, parameterIndex, type) {
return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
@@ -38409,32 +38756,23 @@
}
}
signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
- createTypePredicateFromTypePredicateNode(type, signature.declaration) :
+ createTypePredicateFromTypePredicateNode(type, signature) :
jsdocPredicate || noTypePredicate;
}
ts.Debug.assert(!!signature.resolvedTypePredicate);
}
return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
}
- function createTypePredicateFromTypePredicateNode(node, func) {
+ function createTypePredicateFromTypePredicateNode(node, signature) {
var parameterName = node.parameterName;
var type = getTypeFromTypeNode(node.type);
if (parameterName.kind === 72 /* Identifier */) {
- return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type);
+ return createIdentifierTypePredicate(parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), 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 === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) {
- return i;
- }
- }
- return -1;
- }
function getReturnTypeOfSignature(signature) {
if (!signature.resolvedReturnType) {
if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
@@ -38506,8 +38844,19 @@
}
return undefined;
}
- function getSignatureInstantiation(signature, typeArguments, isJavascript) {
- return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ if (inferredTypeParameters) {
+ var returnSignature = getSingleCallSignature(getReturnTypeOfSignature(instantiatedSignature));
+ if (returnSignature) {
+ var newReturnSignature = cloneSignature(returnSignature);
+ newReturnSignature.typeParameters = inferredTypeParameters;
+ var newInstantiatedSignature = cloneSignature(instantiatedSignature);
+ newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
+ return newInstantiatedSignature;
+ }
+ }
+ return instantiatedSignature;
}
function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
@@ -38702,10 +39051,10 @@
for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
var type = types_5[_i];
if (!(type.flags & excludeKinds)) {
- result |= type.flags;
+ result |= ts.getObjectFlags(type);
}
}
- return result & 939524096 /* PropagatingFlags */;
+ return result & 917504 /* PropagatingFlags */;
}
function createTypeReference(target, typeArguments) {
var id = getTypeListId(typeArguments);
@@ -38713,7 +39062,7 @@
if (!type) {
type = createObjectType(4 /* Reference */, target.symbol);
target.instantiations.set(id, type);
- type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
+ type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
type.target = target;
type.typeArguments = typeArguments;
}
@@ -38879,7 +39228,7 @@
}
function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
- if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
+ if (symbol.valueDeclaration && symbol.valueDeclaration.parent && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
if (jsdocType) {
return jsdocType;
@@ -38900,6 +39249,9 @@
}
}
function getSubstitutionType(typeVariable, substitute) {
+ if (substitute.flags & 3 /* AnyOrUnknown */) {
+ return typeVariable;
+ }
var result = createType(33554432 /* Substitution */);
result.typeVariable = typeVariable;
result.substitute = substitute;
@@ -38915,7 +39267,7 @@
}
function getConstrainedTypeVariable(typeVariable, node) {
var constraints;
- while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) {
+ while (node && !ts.isStatement(node) && node.kind !== 296 /* JSDocComment */) {
var parent = node.parent;
if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) {
var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
@@ -39147,19 +39499,19 @@
function createIterableIteratorType(iteratedType) {
return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]);
}
- function createArrayType(elementType) {
- return createTypeFromGenericGlobalType(globalArrayType, [elementType]);
- }
- function createReadonlyArrayType(elementType) {
- return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]);
+ function createArrayType(elementType, readonly) {
+ return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
}
function getTypeFromArrayTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType));
+ links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType), isReadonlyTypeOperator(node.parent));
}
return links.resolvedType;
}
+ function isReadonlyTypeOperator(node) {
+ return ts.isTypeOperatorNode(node) && node.operator === 133 /* ReadonlyKeyword */;
+ }
// We represent tuple types as type references to synthesized generic interface types created by
// this function. The types are of the form:
//
@@ -39167,7 +39519,7 @@
//
// 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, minLength, hasRestElement, associatedNames) {
+ function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
var typeParameters;
var properties = [];
var maxLength = hasRestElement ? arity - 1 : arity;
@@ -39176,7 +39528,7 @@
for (var i = 0; i < arity; i++) {
var typeParameter = typeParameters[i] = createTypeParameter();
if (i < maxLength) {
- var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i);
+ var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
property.type = typeParameter;
properties.push(property);
}
@@ -39206,25 +39558,27 @@
type.declaredNumberIndexInfo = undefined;
type.minLength = minLength;
type.hasRestElement = hasRestElement;
+ type.readonly = readonly;
type.associatedNames = associatedNames;
return type;
}
- function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) {
- var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
+ function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
+ var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
var type = tupleTypes.get(key);
if (!type) {
- tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames));
+ tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames));
}
return type;
}
- function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) {
+ function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) {
if (minLength === void 0) { minLength = elementTypes.length; }
if (hasRestElement === void 0) { hasRestElement = false; }
+ if (readonly === void 0) { readonly = false; }
var arity = elementTypes.length;
if (arity === 1 && hasRestElement) {
- return createArrayType(elementTypes[0]);
+ return createArrayType(elementTypes[0], readonly);
}
- var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames);
+ var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames);
return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
}
function getTypeFromTupleTypeNode(node) {
@@ -39237,7 +39591,7 @@
var type = getTypeFromTypeNode(n);
return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type;
});
- links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1);
+ links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1, isReadonlyTypeOperator(node.parent));
}
return links.resolvedType;
}
@@ -39247,7 +39601,7 @@
// don't slice off rest element
index = Math.min(index, getTypeReferenceArity(type) - 1);
}
- return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index));
+ return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index));
}
function getTypeFromOptionalTypeNode(node) {
var type = getTypeFromTypeNode(node.type);
@@ -39305,12 +39659,14 @@
// intersections of unit types into 'never' upon construction, but deferring the reduction makes it
// easier to reason about their origin.
if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) {
- includes |= flags & ~939524096 /* ConstructionFlags */;
+ includes |= flags & 1835007 /* IncludesMask */;
+ if (flags & 66846720 /* StructuredOrInstantiable */)
+ includes |= 262144 /* IncludesStructuredOrInstantiable */;
if (type === wildcardType)
- includes |= 268435456 /* Wildcard */;
+ includes |= 4194304 /* IncludesWildcard */;
if (!strictNullChecks && flags & 98304 /* Nullable */) {
- if (!(flags & 134217728 /* ContainsWideningType */))
- includes |= 134217728 /* NonWideningType */;
+ if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */))
+ includes |= 2097152 /* IncludesNonWideningType */;
}
else {
var len = typeSet.length;
@@ -39331,17 +39687,6 @@
}
return includes;
}
- function isSubtypeOfAny(source, targets) {
- for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
- var target = targets_1[_i];
- if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
- !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
- isTypeDerivedFrom(source, target))) {
- return true;
- }
- }
- return false;
- }
function isSetOfLiteralsFromSameEnum(types) {
var first = types[0];
if (first.flags & 1024 /* EnumLiteral */) {
@@ -39356,18 +39701,43 @@
}
return false;
}
- function removeSubtypes(types) {
- if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) {
- return;
+ function removeSubtypes(types, primitivesOnly) {
+ var len = types.length;
+ if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
+ return true;
}
- var i = types.length;
+ var i = len;
+ var count = 0;
while (i > 0) {
i--;
- if (isSubtypeOfAny(types[i], types)) {
+ var source = types[i];
+ for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
+ var target = types_7[_i];
+ if (source !== target) {
+ if (count === 100000) {
+ // After 100000 subtype checks we estimate the remaining amount of work by assuming the
+ // same ratio of checks per element. If the estimated number of remaining type checks is
+ // greater than an upper limit we deem the union type too complex to represent. The
+ // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
+ // caps union types at 5000 unique literal types and 1000 unique object types.
+ var estimatedCount = (count / (len - i)) * len;
+ if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
+ error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
+ return false;
+ }
+ }
+ count++;
+ if (isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
+ !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
+ isTypeDerivedFrom(source, target))) {
ts.orderedRemoveItemAt(types, i);
+ break;
}
}
}
+ }
+ return true;
+ }
function removeRedundantLiteralTypes(types, includes) {
var i = types.length;
while (i > 0) {
@@ -39402,25 +39772,27 @@
var includes = addTypesToUnion(typeSet, 0, types);
if (unionReduction !== 0 /* None */) {
if (includes & 3 /* AnyOrUnknown */) {
- return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType;
+ return includes & 1 /* Any */ ? includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
}
switch (unionReduction) {
case 1 /* Literal */:
- if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) {
+ if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
removeRedundantLiteralTypes(typeSet, includes);
}
break;
case 2 /* Subtype */:
- removeSubtypes(typeSet);
+ if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
+ return errorType;
+ }
break;
}
if (typeSet.length === 0) {
- return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType :
- includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType :
+ return includes & 65536 /* Null */ ? includes & 2097152 /* IncludesNonWideningType */ ? nullType : nullWideningType :
+ includes & 32768 /* Undefined */ ? includes & 2097152 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
neverType;
}
}
- return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments);
+ return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments);
}
function getUnionTypePredicate(signatures) {
var first;
@@ -39457,7 +39829,7 @@
: !ts.isIdentifierTypePredicate(b);
}
// This function assumes the constituent type list is sorted and deduplicated.
- function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) {
+ function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
if (types.length === 0) {
return neverType;
}
@@ -39467,11 +39839,10 @@
var id = getTypeListId(types);
var type = unionTypes.get(id);
if (!type) {
- var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
- type = createType(1048576 /* Union */ | propagatedFlags);
+ type = createType(1048576 /* Union */);
unionTypes.set(id, type);
+ type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
type.types = types;
- type.primitiveTypesOnly = primitiveTypesOnly;
/*
Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
@@ -39497,16 +39868,16 @@
return addTypesToIntersection(typeSet, includes, type.types);
}
if (isEmptyAnonymousObjectType(type)) {
- if (!(includes & 536870912 /* EmptyObject */)) {
- includes |= 536870912 /* EmptyObject */;
+ if (!(includes & 8388608 /* IncludesEmptyObject */)) {
+ includes |= 8388608 /* IncludesEmptyObject */;
typeSet.push(type);
}
}
else {
- includes |= flags & ~939524096 /* ConstructionFlags */;
+ includes |= flags & 1835007 /* IncludesMask */;
if (flags & 3 /* AnyOrUnknown */) {
if (type === wildcardType)
- includes |= 268435456 /* Wildcard */;
+ includes |= 4194304 /* IncludesWildcard */;
}
else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) {
typeSet.push(type);
@@ -39517,8 +39888,8 @@
// Add the given types to the given type set. Order is preserved, freshness is removed from literal
// types, duplicates are removed, and nested types of the given kind are flattened into the set.
function addTypesToIntersection(typeSet, includes, types) {
- for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
- var type = types_7[_i];
+ for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
+ var type = types_8[_i];
includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
}
return includes;
@@ -39561,7 +39932,7 @@
// 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 & 1048576 /* Union */) && t.primitiveTypesOnly; });
+ var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); });
if (index < 0) {
return false;
}
@@ -39570,7 +39941,7 @@
// the unionTypes array.
while (i < types.length) {
var t = types[i];
- if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) {
+ if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) {
(unionTypes || (unionTypes = [types[index]])).push(t);
ts.orderedRemoveItemAt(types, i);
}
@@ -39599,7 +39970,7 @@
}
}
// Finally replace the first union with the result
- types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true);
+ types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */);
return true;
}
// We normalize combinations of intersection and union types based on the distributive property of the '&'
@@ -39619,7 +39990,7 @@
return neverType;
}
if (includes & 1 /* Any */) {
- return includes & 268435456 /* Wildcard */ ? wildcardType : anyType;
+ return includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType;
}
if (!strictNullChecks && includes & 98304 /* Nullable */) {
return includes & 32768 /* Undefined */ ? undefinedType : nullType;
@@ -39630,7 +40001,7 @@
includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
removeRedundantPrimitiveTypes(typeSet, includes);
}
- if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) {
+ if (includes & 8388608 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
}
if (typeSet.length === 0) {
@@ -39655,9 +40026,9 @@
var id = getTypeListId(typeSet);
var type = intersectionTypes.get(id);
if (!type) {
- var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */);
- type = createType(2097152 /* Intersection */ | propagatedFlags);
+ type = createType(2097152 /* Intersection */);
intersectionTypes.set(id, type);
+ type.objectFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */);
type.types = typeSet;
type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
type.aliasTypeArguments = aliasTypeArguments;
@@ -39712,7 +40083,7 @@
return neverType;
}
function getLiteralTypeFromProperties(type, include) {
- return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); }));
+ return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
}
function getNonEnumNumberIndexInfo(type) {
var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
@@ -39754,6 +40125,9 @@
? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
: errorType;
break;
+ case 133 /* ReadonlyKeyword */:
+ links.resolvedType = getTypeFromTypeNode(node.type);
+ break;
}
}
return links.resolvedType; // TODO: GH#18217
@@ -39856,7 +40230,10 @@
return anyType;
}
if (accessExpression && !isConstEnumObjectType(objectType)) {
- if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
+ if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
+ error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
+ }
+ else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
}
@@ -39908,7 +40285,7 @@
: accessNode;
}
function isGenericObjectType(type) {
- return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */);
+ return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 131072 /* GenericMappedType */);
}
function isGenericIndexType(type) {
return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */);
@@ -39954,12 +40331,15 @@
// that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
// construct the type Box<T[X]>.
if (isGenericMappedType(objectType)) {
- var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
- var templateMapper = combineTypeMappers(objectType.mapper, mapper);
- return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType);
+ return type.simplified = mapType(substituteIndexedMappedType(objectType, type.indexType), getSimplifiedType);
}
return type.simplified = type;
}
+ function substituteIndexedMappedType(objectType, index) {
+ var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
+ var templateMapper = combineTypeMappers(objectType.mapper, mapper);
+ return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
+ }
function getIndexedAccessType(objectType, indexType, accessNode, missingType) {
if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; }
if (objectType === wildcardType || indexType === wildcardType) {
@@ -40041,13 +40421,48 @@
function getActualTypeVariable(type) {
return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type;
}
+ /**
+ * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
+ */
+ function isIntersectionEmpty(type1, type2) {
+ return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
+ }
function getConditionalType(root, mapper) {
var checkType = instantiateType(root.checkType, mapper);
var extendsType = instantiateType(root.extendsType, mapper);
if (checkType === wildcardType || extendsType === wildcardType) {
return wildcardType;
}
- var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */);
+ var trueType = instantiateType(root.trueType, mapper);
+ var falseType = instantiateType(root.falseType, mapper);
+ var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType);
+ var result = conditionalTypes.get(instantiationId);
+ if (result) {
+ return result;
+ }
+ var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType);
+ conditionalTypes.set(instantiationId, newResult);
+ return newResult;
+ }
+ function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) {
+ // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
+ if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
+ if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
+ return trueType;
+ }
+ else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
+ return neverType;
+ }
+ }
+ else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
+ if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
+ return neverType;
+ }
+ else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
+ return falseType;
+ }
+ }
+ var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */);
var combinedMapper;
if (root.inferTypeParameters) {
var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
@@ -40057,25 +40472,25 @@
// types rules (i.e. proper contravariance) for inferences.
inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
}
- combinedMapper = combineTypeMappers(mapper, context);
+ combinedMapper = combineTypeMappers(mapper, context.mapper);
}
// Instantiate the extends type including inferences for 'infer T' type parameters
var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
// We attempt to resolve the conditional type only when the check and extends types are non-generic
- if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */)) {
+ if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */)) {
if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) {
- return instantiateType(root.trueType, mapper);
+ return trueType;
}
// Return union of trueType and falseType for 'any' since it matches anything
if (checkType.flags & 1 /* Any */) {
- return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]);
+ return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), falseType]);
}
- // Return falseType for a definitely false extends check. We check an instantations of the two
+ // Return falseType for a definitely false extends check. We check an instantiations of the two
// types with type parameters mapped to the wildcard type, the most permissive instantiations
// possible (the wildcard type is assignable to and from all types). If those are not related,
- // then no instatiations will be and we can just return the false branch type.
+ // then no instantiations will be and we can just return the false branch type.
if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) {
- return instantiateType(root.falseType, mapper);
+ return falseType;
}
// Return trueType for a definitely true extends check. We check instantiations of the two
// types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
@@ -40087,6 +40502,9 @@
}
}
// Return a deferred type for a check that is neither definitely true nor definitely false
+ return getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType);
+ }
+ function getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType) {
var erasedCheckType = getActualTypeVariable(checkType);
var result = createType(16777216 /* Conditional */);
result.root = root;
@@ -40094,15 +40512,14 @@
result.extendsType = extendsType;
result.mapper = mapper;
result.combinedMapper = combinedMapper;
+ result.trueType = trueType;
+ result.falseType = falseType;
result.aliasSymbol = root.aliasSymbol;
result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
return result;
}
- function getTrueTypeFromConditionalType(type) {
- return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
- }
- function getFalseTypeFromConditionalType(type) {
- return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
+ function getInferredTrueTypeFromConditionalType(type) {
+ return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper || type.mapper));
}
function getInferTypeParameters(node) {
var result;
@@ -40271,7 +40688,7 @@
* this function should be called in a left folding style, with left = previous result of getSpreadType
* and right = the new element to be spread.
*/
- function getSpreadType(left, right, symbol, typeFlags, objectFlags) {
+ function getSpreadType(left, right, symbol, objectFlags, readonly) {
if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
return anyType;
}
@@ -40285,10 +40702,10 @@
return left;
}
if (left.flags & 1048576 /* Union */) {
- return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); });
+ return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
}
if (right.flags & 1048576 /* Union */) {
- return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); });
+ return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
}
if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
return left;
@@ -40304,7 +40721,7 @@
var types = left.types;
var lastLeft = types[types.length - 1];
if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
- return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)]));
+ return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
}
}
return getIntersectionType([left, right]);
@@ -40328,7 +40745,7 @@
skippedPrivateMembers.set(rightProp.escapedName, true);
}
else if (isSpreadableProperty(rightProp)) {
- members.set(rightProp.escapedName, getSpreadSymbol(rightProp));
+ members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
}
}
for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
@@ -40352,12 +40769,11 @@
}
}
else {
- members.set(leftProp.escapedName, getSpreadSymbol(leftProp));
+ members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
}
}
- var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo));
- spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags;
- spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
+ var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
+ spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
return spread;
}
/** We approximate own properties as non-methods plus methods that are inside the object literal */
@@ -40365,25 +40781,21 @@
return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
!prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); });
}
- function getSpreadSymbol(prop) {
- var isReadonly = isReadonlySymbol(prop);
+ function getSpreadSymbol(prop, readonly) {
var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
- if (!isReadonly && !isSetonlyAccessor) {
+ if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
return prop;
}
var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
- var result = createSymbol(flags, prop.escapedName);
+ var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
result.declarations = prop.declarations;
result.nameType = prop.nameType;
result.syntheticOrigin = prop;
return result;
}
- function getNonReadonlyIndexSignature(index) {
- if (index && index.isReadonly) {
- return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration);
- }
- return index;
+ function getIndexInfoWithReadonly(info, readonly) {
+ return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
}
function createLiteralType(flags, value, symbol) {
var type = createType(flags);
@@ -40471,8 +40883,8 @@
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 120 /* AnyKeyword */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return anyType;
case 143 /* UnknownKeyword */:
return unknownType;
@@ -40519,23 +40931,23 @@
return getTypeFromUnionTypeNode(node);
case 174 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return getTypeFromJSDocNullableTypeNode(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return addOptionality(getTypeFromTypeNode(node.type));
case 177 /* ParenthesizedType */:
case 172 /* RestType */:
- case 287 /* JSDocNonNullableType */:
- case 283 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 288 /* JSDocTypeExpression */:
return getTypeFromTypeNode(node.type);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 297 /* JSDocTypeLiteral */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 179 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
@@ -40611,16 +41023,8 @@
* Maps forward-references to later types parameters to the empty object type.
* This is used during inference when instantiating type parameter defaults.
*/
- function createBackreferenceMapper(typeParameters, index) {
- return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; };
- }
- function isInferenceContext(mapper) {
- return !!mapper.typeParameters;
- }
- function cloneTypeMapper(mapper) {
- return mapper && isInferenceContext(mapper) ?
- createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) :
- mapper;
+ function createBackreferenceMapper(context, index) {
+ return function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? emptyObjectType : t; };
}
function combineTypeMappers(mapper1, mapper2) {
if (!mapper1)
@@ -40703,7 +41107,7 @@
}
// 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) & (2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */));
+ var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */));
result.declarations = symbol.declarations;
result.parent = symbol.parent;
result.target = symbol;
@@ -40799,7 +41203,7 @@
function getHomomorphicTypeVariable(type) {
var constraintType = getConstraintTypeFromMappedType(type);
if (constraintType.flags & 4194304 /* Index */) {
- var typeVariable = constraintType.type;
+ var typeVariable = getActualTypeVariable(constraintType.type);
if (typeVariable.flags & 262144 /* TypeParameter */) {
return typeVariable;
}
@@ -40821,30 +41225,27 @@
if (typeVariable) {
var mappedTypeVariable = instantiateType(typeVariable, mapper);
if (typeVariable !== mappedTypeVariable) {
- // If we are already in the process of creating an instantiation of this mapped type,
- // return the error type. This situation only arises if we are instantiating the mapped
- // type for an array or tuple type, as we then need to eagerly resolve the (possibly
- // circular) element type(s).
- if (type.instantiating) {
- return errorType;
- }
- type.instantiating = true;
- var result = mapType(mappedTypeVariable, function (t) {
- if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) {
+ return mapType(mappedTypeVariable, function (t) {
+ if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
var replacementMapper = createReplacementMapper(typeVariable, t, mapper);
- return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
- isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) :
+ return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
instantiateAnonymousType(type, replacementMapper);
}
return t;
});
- type.instantiating = false;
- return result;
}
}
return instantiateAnonymousType(type, mapper);
}
+ function getModifiedReadonlyState(state, modifiers) {
+ return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
+ }
+ function instantiateMappedArrayType(arrayType, mappedType, mapper) {
+ var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
+ return elementType === errorType ? errorType :
+ createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
+ }
function instantiateMappedTupleType(tupleType, mappedType, mapper) {
var minLength = tupleType.target.minLength;
var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) {
@@ -40854,7 +41255,9 @@
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);
+ var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
+ return ts.contains(elementTypes, errorType) ? errorType :
+ createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames);
}
function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key]));
@@ -40920,6 +41323,7 @@
// We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
// with a combination of infinite generic types that perpetually generate new type identities. We stop
// the recursion here by yielding the error type.
+ error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
return errorType;
}
instantiationDepth++;
@@ -40971,7 +41375,17 @@
return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
}
if (flags & 33554432 /* Substitution */) {
- return instantiateType(type.typeVariable, mapper);
+ var maybeVariable = instantiateType(type.typeVariable, mapper);
+ if (maybeVariable.flags & 8650752 /* TypeVariable */) {
+ return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
+ }
+ else {
+ var sub = instantiateType(type.substitute, mapper);
+ if (sub.flags & 3 /* AnyOrUnknown */ || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
+ return maybeVariable;
+ }
+ return sub;
+ }
}
return type;
}
@@ -40980,8 +41394,20 @@
type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
}
function getRestrictiveInstantiation(type) {
- return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
- type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper));
+ if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
+ return type;
+ }
+ if (type.restrictiveInstantiation) {
+ return type.restrictiveInstantiation;
+ }
+ type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
+ // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
+ // which is redundant - we'll produce new type identities, but all type params have already been mapped.
+ // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
+ // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
+ // are constrained to `unknown` and produce tons of false positives/negatives!
+ type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
+ return type.restrictiveInstantiation;
}
function instantiateIndexInfo(info, mapper) {
return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
@@ -41180,7 +41606,7 @@
var resultObj = {};
checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj);
var diagnostic = resultObj.error;
- addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
+ ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression));
return true;
}
}
@@ -41215,7 +41641,7 @@
checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj);
if (resultObj.error) {
if (target.symbol && ts.length(target.symbol.declarations)) {
- addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
+ ts.addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature));
}
return true;
}
@@ -41262,13 +41688,13 @@
undefined;
if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
issuedElaboration = true;
- addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
+ ts.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))) {
var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
- addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
+ ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target)));
}
}
}
@@ -41339,7 +41765,7 @@
// child is of the type of the expression
return { errorNode: child, innerExpression: child.expression, nameType: nameType };
case 11 /* JsxText */:
- if (child.containsOnlyWhiteSpaces) {
+ if (child.containsOnlyTriviaWhiteSpaces) {
break; // Whitespace only jsx text isn't real jsx text
}
// child is a string
@@ -41362,7 +41788,7 @@
var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
var childrenNameType = getLiteralType(childrenPropName);
var childrenTargetType = getIndexedAccessType(target, childrenNameType);
- var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyWhiteSpaces; });
+ var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
if (!ts.length(validChildren)) {
return result;
}
@@ -41450,7 +41876,7 @@
return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation);
}
// recreate a tuple from the elements, if possible
- var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true);
+ var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
if (isTupleLikeType(tupleizedType)) {
return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation);
}
@@ -41516,6 +41942,14 @@
/*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */;
}
/**
+ * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
+ */
+ function isAnySignature(s) {
+ return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
+ s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
+ isTypeAny(getReturnTypeOfSignature(s));
+ }
+ /**
* See signatureRelatedTo, compareSignaturesIdentical
*/
function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) {
@@ -41523,13 +41957,16 @@
if (source === target) {
return -1 /* True */;
}
+ if (isAnySignature(target)) {
+ return -1 /* True */;
+ }
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);
+ source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
}
var sourceCount = getParameterCount(source);
var sourceRestType = getNonArrayRestType(source);
@@ -41600,7 +42037,7 @@
if (targetTypePredicate) {
var sourceTypePredicate = getTypePredicateOfSignature(source);
if (sourceTypePredicate) {
- result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217
+ result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
}
else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
if (reportErrors) {
@@ -41619,7 +42056,7 @@
}
return result;
}
- function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) {
+ function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
if (source.kind !== target.kind) {
if (reportErrors) {
errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
@@ -41628,12 +42065,9 @@
return 0 /* False */;
}
if (source.kind === 1 /* Identifier */) {
- var targetPredicate = target;
- var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0);
- var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0);
- if (sourceIndex !== targetIndex) {
+ if (source.parameterIndex !== target.parameterIndex) {
if (reportErrors) {
- errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName);
+ errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
}
return 0 /* False */;
@@ -41834,7 +42268,7 @@
}
var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
if (relatedInfo) {
- addRelatedInfo.apply(void 0, [diag].concat(relatedInfo));
+ ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInfo));
}
if (errorOutputContainer) {
errorOutputContainer.error = diag;
@@ -42441,8 +42875,8 @@
if (source.root.isDistributive === target.root.isDistributive) {
if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
- if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
- if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
+ if (result_3 &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) {
+ if (result_3 &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) {
return result_3;
}
}
@@ -42457,6 +42891,7 @@
}
var result;
var originalErrorInfo;
+ var varianceCheckFailed = false;
var saveErrorInfo = errorInfo;
// We limit alias variance probing to only object and conditional types since their alias behavior
// is more predictable than other, interned types, which may or may not have an alias depending on
@@ -42465,11 +42900,10 @@
source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
!(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
var variances = getAliasVariances(source.aliasSymbol);
- if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) {
- return result;
+ var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances);
+ if (varianceResult !== undefined) {
+ return varianceResult;
}
- originalErrorInfo = errorInfo;
- errorInfo = saveErrorInfo;
}
if (target.flags & 262144 /* TypeParameter */) {
// A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q].
@@ -42526,9 +42960,18 @@
template.indexType === getTypeParameterFromMappedType(target)) {
return -1 /* True */;
}
+ if (!isGenericMappedType(source)) {
+ var targetConstraint = getConstraintTypeFromMappedType(target);
+ var sourceKeys_1 = getIndexType(source);
+ var hasOptionalUnionKeys = modifiers & 4 /* IncludeOptional */ && targetConstraint.flags & 1048576 /* Union */;
+ var filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, function (t) { return !!isRelatedTo(t, sourceKeys_1); }) : undefined;
// A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X.
- if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) {
- var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target));
+ // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X.
+ if (hasOptionalUnionKeys
+ ? !(filteredByApplicability.flags & 131072 /* Never */)
+ : isRelatedTo(targetConstraint, sourceKeys_1)) {
+ var indexingType = hasOptionalUnionKeys ? filteredByApplicability : getTypeParameterFromMappedType(target);
+ var indexedAccessType = getIndexedAccessType(source, indexingType);
var templateType = getTemplateTypeFromMappedType(target);
if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
return result;
@@ -42538,6 +42981,7 @@
errorInfo = saveErrorInfo;
}
}
+ }
if (source.flags & 8650752 /* TypeVariable */) {
if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
// A type S[K] is related to a type T[J] if S is related to T and K is related to J.
@@ -42581,8 +43025,8 @@
// and Y1 is related to Y2.
if (isTypeIdenticalTo(source.extendsType, target.extendsType) &&
(isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
- if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) {
- result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
+ if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) {
+ result &= isRelatedTo(source.falseType, target.falseType, reportErrors);
}
if (result) {
errorInfo = saveErrorInfo;
@@ -42631,36 +43075,19 @@
// type references (which are intended by be compared structurally). Obtain the variance
// information for the type parameters and relate the type arguments accordingly.
var variances = getVariances(source.target);
- if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) {
- return result;
- }
- // The type arguments did not relate appropriately, but it may be because we have no variance
- // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
- // arguments). It might also be the case that the target type has a 'void' type argument for
- // a covariant type parameter that is only used in return positions within the generic type
- // (in which case any type argument is permitted on the source side). In those cases we proceed
- // with a structural comparison. Otherwise, we know for certain the instantiations aren't
- // related and we can return here.
- if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) {
- // In some cases generic types that are covariant in regular type checking mode become
- // invariant in --strictFunctionTypes mode because one or more type parameters are used in
- // both co- and contravariant positions. In order to make it easier to diagnose *why* such
- // types are invariant, if any of the type parameters are invariant we reset the reported
- // errors and instead force a structural comparison (which will include elaborations that
- // reveal the reason).
- if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) {
- return 0 /* False */;
- }
- // We remember the original error information so we can restore it in case the structural
- // comparison unexpectedly succeeds. This can happen when the structural comparison result
- // is a Ternary.Maybe for example caused by the recursion depth limiter.
- originalErrorInfo = errorInfo;
- errorInfo = saveErrorInfo;
+ var varianceResult = relateVariances(source.typeArguments, target.typeArguments, variances);
+ if (varianceResult !== undefined) {
+ return varianceResult;
}
}
- else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) {
+ else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
}
+ // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
+ // and not `{} <- fresh({}) <- {[idx: string]: any}`
+ else if (relation === subtypeRelation && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
+ return 0 /* False */;
+ }
// Even if relationship doesn't hold for unions, intersections, or generic type references,
// it may hold in a structural comparison.
// In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
@@ -42682,17 +43109,57 @@
}
}
}
- if (result) {
- if (!originalErrorInfo) {
- errorInfo = saveErrorInfo;
+ if (varianceCheckFailed && result) {
+ errorInfo = originalErrorInfo || errorInfo || saveErrorInfo; // Use variance error (there is no structural one) and return false
+ }
+ else if (result) {
return result;
}
- errorInfo = originalErrorInfo;
}
}
+ return 0 /* False */;
+ function isNonGeneric(type) {
+ // If we're already in identity relationship checking, we should use `isRelatedTo`
+ // to catch the `Maybe` from an excessively deep type (which we then assume means
+ // that the type could possibly contain a generic)
+ if (relation === identityRelation) {
+ return isRelatedTo(type, getPermissiveInstantiation(type)) === -1 /* True */;
+ }
+ return isTypeIdenticalTo(type, getPermissiveInstantiation(type));
}
+ function relateVariances(sourceTypeArguments, targetTypeArguments, variances) {
+ if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors)) {
+ return result;
+ }
+ var allowStructuralFallback = (targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances)) || isNonGeneric(source) || isNonGeneric(target);
+ varianceCheckFailed = !allowStructuralFallback;
+ // The type arguments did not relate appropriately, but it may be because we have no variance
+ // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
+ // arguments). It might also be the case that the target type has a 'void' type argument for
+ // a covariant type parameter that is only used in return positions within the generic type
+ // (in which case any type argument is permitted on the source side). In those cases we proceed
+ // with a structural comparison. Otherwise, we know for certain the instantiations aren't
+ // related and we can return here.
+ if (variances !== ts.emptyArray && !allowStructuralFallback) {
+ // In some cases generic types that are covariant in regular type checking mode become
+ // invariant in --strictFunctionTypes mode because one or more type parameters are used in
+ // both co- and contravariant positions. In order to make it easier to diagnose *why* such
+ // types are invariant, if any of the type parameters are invariant we reset the reported
+ // errors and instead force a structural comparison (which will include elaborations that
+ // reveal the reason).
+ // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
+ // we can return `False` early here to skip calculating the structural error message we don't need.
+ if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) {
return 0 /* False */;
}
+ // We remember the original error information so we can restore it in case the structural
+ // comparison unexpectedly succeeds. This can happen when the structural comparison result
+ // is a Ternary.Maybe for example caused by the recursion depth limiter.
+ originalErrorInfo = errorInfo;
+ errorInfo = saveErrorInfo;
+ }
+ }
+ }
// A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
// related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
// that S and T are contra-variant whereas X and Y are co-variant.
@@ -43171,20 +43638,17 @@
return variances;
}
function getVariances(type) {
- if (!strictFunctionTypes) {
- return ts.emptyArray;
- }
- if (type === globalArrayType || type === globalReadonlyArrayType) {
- // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters)
+ // Arrays and tuples are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters)
+ if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
return ts.emptyArray;
}
return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
}
// Return true if the given type reference has a 'void' type argument for a covariant type parameter.
// See comment at call in recursiveTypeRelatedTo for when this case matters.
- function hasCovariantVoidArgument(type, variances) {
+ function hasCovariantVoidArgument(typeArguments, variances) {
for (var i = 0; i < variances.length; i++) {
- if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) {
+ if (variances[i] === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
return true;
}
}
@@ -43413,8 +43877,8 @@
}
function literalTypesWithSameBaseType(types) {
var commonBaseType;
- for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
- var t = types_8[_i];
+ for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
+ var t = types_9[_i];
var baseType = getBaseTypeOfLiteralType(t);
if (!commonBaseType) {
commonBaseType = baseType;
@@ -43447,7 +43911,7 @@
return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
}
function isArrayType(type) {
- return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType;
+ return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
}
function isReadonlyArrayType(type) {
return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
@@ -43458,8 +43922,7 @@
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<any>
- return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) ||
- !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
+ return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
}
function isEmptyArrayLiteralType(type) {
var elementType = isArrayType(type) ? type.typeArguments[0] : undefined;
@@ -43544,8 +44007,8 @@
}
function getFalsyFlagsOfTypes(types) {
var result = 0;
- for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
- var t = types_9[_i];
+ for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
+ var t = types_10[_i];
result |= getFalsyFlags(t);
}
return result;
@@ -43659,7 +44122,7 @@
var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
regularNew.flags = resolved.flags;
- regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */);
+ regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
type.regularType = regularNew;
return regularNew;
}
@@ -43738,14 +44201,14 @@
var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
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
+ result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening
return result;
}
function getWidenedType(type) {
return getWidenedTypeWithContext(type, /*context*/ undefined);
}
function getWidenedTypeWithContext(type, context) {
- if (type.flags & 402653184 /* RequiresWidening */) {
+ if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) {
if (type.flags & 98304 /* Nullable */) {
return anyType;
}
@@ -43782,7 +44245,7 @@
*/
function reportWideningErrorsInType(type) {
var errorReported = false;
- if (type.flags & 134217728 /* ContainsWideningType */) {
+ if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) {
if (type.flags & 1048576 /* Union */) {
if (ts.some(type.types, isEmptyObjectType)) {
errorReported = true;
@@ -43808,7 +44271,7 @@
for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
var p = _e[_d];
var t = getTypeOfSymbol(p);
- if (t.flags & 134217728 /* ContainsWideningType */) {
+ if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) {
if (!reportWideningErrorsInType(t)) {
error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
}
@@ -43854,7 +44317,7 @@
return;
}
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
return;
case 239 /* FunctionDeclaration */:
@@ -43881,14 +44344,14 @@
errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
}
function reportErrorsFromWidening(declaration, type) {
- if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) {
+ if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) {
// Report implicit any error within type if possible, otherwise report error on declaration
if (!reportWideningErrorsInType(type)) {
reportImplicitAny(declaration, type);
}
}
}
- function forEachMatchingParameterType(source, target, callback) {
+ function applyToParameterTypes(source, target, callback) {
var sourceCount = getParameterCount(source);
var targetCount = getParameterCount(target);
var sourceRestType = getEffectiveRestType(source);
@@ -43909,25 +44372,55 @@
callback(getRestTypeAtPosition(source, paramCount), targetRestType);
}
}
- function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) {
- var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo);
- var context = mapper;
- context.typeParameters = typeParameters;
- context.signature = signature;
- context.inferences = inferences;
- context.flags = flags;
- context.compareTypes = compareTypes || compareTypesAssignable;
+ function applyToReturnTypes(source, target, callback) {
+ var sourceTypePredicate = getTypePredicateOfSignature(source);
+ var targetTypePredicate = getTypePredicateOfSignature(target);
+ if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind &&
+ (sourceTypePredicate.kind === 0 /* This */ || sourceTypePredicate.parameterIndex === targetTypePredicate.parameterIndex)) {
+ callback(sourceTypePredicate.type, targetTypePredicate.type);
+ }
+ else {
+ callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
+ }
+ }
+ function createInferenceContext(typeParameters, signature, flags, compareTypes) {
+ return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
+ }
+ function cloneInferenceContext(context, extraFlags) {
+ if (extraFlags === void 0) { extraFlags = 0; }
+ return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
+ }
+ function cloneInferredPartOfContext(context) {
+ var inferences = ts.filter(context.inferences, hasInferenceCandidates);
+ return inferences.length ?
+ createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
+ undefined;
+ }
+ function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
+ var context = {
+ inferences: inferences,
+ signature: signature,
+ flags: flags,
+ compareTypes: compareTypes,
+ mapper: function (t) { return mapToInferredType(context, t, /*fix*/ true); },
+ nonFixingMapper: function (t) { return mapToInferredType(context, t, /*fix*/ false); },
+ };
return context;
- function mapper(t) {
+ }
+ function mapToInferredType(context, t, fix) {
+ var inferences = context.inferences;
for (var i = 0; i < inferences.length; i++) {
- if (t === inferences[i].typeParameter) {
- inferences[i].isFixed = true;
+ var inference = inferences[i];
+ if (t === inference.typeParameter) {
+ if (fix && !inference.isFixed) {
+ inference.isFixed = true;
+ inference.inferredType = undefined;
+ }
return getInferredType(context, i);
}
}
return t;
}
- }
function createInferenceInfo(typeParameter) {
return {
typeParameter: typeParameter,
@@ -43950,6 +44443,9 @@
isFixed: inference.isFixed
};
}
+ function getMapperFromContext(context) {
+ return context && context.mapper;
+ }
// Return true if the given type could possibly reference a type parameter for which
// we perform type inference (i.e. a type parameter of a generic function). We cache
// results for union and intersection types for performance reasons.
@@ -44006,31 +44502,21 @@
return type;
}
function createReverseMappedType(source, target, constraint) {
- var properties = getPropertiesOfType(source);
- if (properties.length === 0 && !getIndexInfoOfType(source, 0 /* String */)) {
- return undefined;
- }
// If any property contains context sensitive functions that have been skipped, the source type
// is incomplete and we can't infer a meaningful input type.
- for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
- var prop = properties_3[_i];
- if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) {
+ if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || getPropertiesOfType(source).length === 0 && !getIndexInfoOfType(source, 0 /* String */)) {
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, constraint));
- }
- if (isReadonlyArrayType(source)) {
- return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint));
+ return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint), isReadonlyArrayType(source));
}
if (isTupleType(source)) {
var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); });
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);
+ return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, 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.
@@ -44051,16 +44537,16 @@
return getTypeFromInference(inference);
}
function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
- var properties, _i, properties_4, targetProp, sourceProp, targetType, sourceType;
+ var properties, _i, properties_3, targetProp, sourceProp, targetType, sourceType;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
properties = target.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target);
- _i = 0, properties_4 = properties;
+ _i = 0, properties_3 = properties;
_a.label = 1;
case 1:
- if (!(_i < properties_4.length)) return [3 /*break*/, 6];
- targetProp = properties_4[_i];
+ if (!(_i < properties_3.length)) return [3 /*break*/, 6];
+ targetProp = properties_3[_i];
if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 5];
sourceProp = getPropertyOfType(source, targetProp.escapedName);
if (!!sourceProp) return [3 /*break*/, 3];
@@ -44104,11 +44590,11 @@
inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
emptyObjectType;
}
- function inferTypes(inferences, originalSource, originalTarget, priority) {
+ function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
if (priority === void 0) { priority = 0; }
+ if (contravariant === void 0) { contravariant = false; }
var symbolStack;
var visited;
- var contravariant = false;
var bivariant = false;
var propagationType;
var allowComplexConstraintInference = true;
@@ -44184,7 +44670,7 @@
// not contain anyFunctionType when we come back to this argument for its second round
// of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
// when constructing types from type parameters that had no inference candidates).
- if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) {
+ if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) {
return;
}
var inference = getInferenceInfoForType(target);
@@ -44193,6 +44679,7 @@
if (inference.priority === undefined || priority < inference.priority) {
inference.candidates = undefined;
inference.contraCandidates = undefined;
+ inference.topLevel = true;
inference.priority = priority;
}
if (priority === inference.priority) {
@@ -44200,14 +44687,19 @@
// We make contravariant inferences only if we are in a pure contravariant position,
// i.e. only if we have not descended into a bivariant position.
if (contravariant && !bivariant) {
- inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate);
+ if (!ts.contains(inference.contraCandidates, candidate)) {
+ inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
+ inference.inferredType = undefined;
}
- else {
- inference.candidates = ts.appendIfUnique(inference.candidates, candidate);
+ }
+ else if (!ts.contains(inference.candidates, candidate)) {
+ inference.candidates = ts.append(inference.candidates, candidate);
+ inference.inferredType = undefined;
}
}
- if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) {
+ if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
inference.topLevel = false;
+ inference.inferredType = undefined;
}
}
return;
@@ -44231,6 +44723,9 @@
}
}
}
+ else if (target.flags & 33554432 /* Substitution */) {
+ inferFromTypes(source, target.typeVariable);
+ }
if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) {
// If source and target are references to the same generic type, infer from type arguments
var sourceTypes = source.typeArguments || ts.emptyArray;
@@ -44267,42 +44762,48 @@
else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) {
inferFromTypes(source.checkType, target.checkType);
inferFromTypes(source.extendsType, target.extendsType);
- inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
- inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
+ inferFromTypes(source.trueType, target.trueType);
+ inferFromTypes(source.falseType, target.falseType);
}
- else if (target.flags & 16777216 /* Conditional */) {
- inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]));
+ else if (target.flags & 16777216 /* Conditional */ && !contravariant) {
+ inferFromTypes(source, target.trueType);
+ inferFromTypes(source, target.falseType);
}
else if (target.flags & 3145728 /* UnionOrIntersection */) {
- var targetTypes = target.types;
+ // We infer from types that are not naked type variables first so that inferences we
+ // make from nested naked type variables and given slightly higher priority by virtue
+ // of being first in the candidates array.
var typeVariableCount = 0;
- var typeVariable = void 0;
- // First infer to each type in union or intersection that isn't a type variable
- for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) {
- var t = targetTypes_3[_d];
+ for (var _d = 0, _e = target.types; _d < _e.length; _d++) {
+ var t = _e[_d];
if (getInferenceInfoForType(t)) {
- typeVariable = t;
typeVariableCount++;
}
else {
inferFromTypes(source, t);
}
}
- // Next, if target containings a single naked type variable, make a secondary inference to that type
- // variable. This gives meaningful results for union types in co-variant positions and intersection
- // types in contra-variant positions (such as callback parameters).
- if (typeVariableCount === 1) {
+ // Inferences directly to naked type variables are given lower priority as they are
+ // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
+ // we want to infer string for T, not Promise<string> | string. For intersection types
+ // we only infer to single naked type variables.
+ if (target.flags & 1048576 /* Union */ ? typeVariableCount !== 0 : typeVariableCount === 1) {
var savePriority = priority;
priority |= 1 /* NakedTypeVariable */;
- inferFromTypes(source, typeVariable);
+ for (var _f = 0, _g = target.types; _f < _g.length; _f++) {
+ var t = _g[_f];
+ if (getInferenceInfoForType(t)) {
+ inferFromTypes(source, t);
+ }
+ }
priority = savePriority;
}
}
else if (source.flags & 1048576 /* Union */) {
// Source is a union or intersection type, infer from each constituent type
var sourceTypes = source.types;
- for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) {
- var sourceType = sourceTypes_3[_e];
+ for (var _h = 0, sourceTypes_3 = sourceTypes; _h < sourceTypes_3.length; _h++) {
+ var sourceType = sourceTypes_3[_h];
inferFromTypes(sourceType, target);
}
}
@@ -44318,7 +44819,7 @@
// that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
// here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
// (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
- // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just
+ // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
// remove this `allowComplexConstraintInference` flag.
allowComplexConstraintInference = false;
return inferFromTypes(apparentSource, target);
@@ -44380,12 +44881,12 @@
}
return undefined;
}
- function inferFromMappedTypeConstraint(source, target, constraintType) {
+ function inferToMappedType(source, target, constraintType) {
if (constraintType.flags & 1048576 /* Union */) {
var result = false;
for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
var type = _a[_i];
- result = inferFromMappedTypeConstraint(source, target, type) || result;
+ result = inferToMappedType(source, target, type) || result;
}
return result;
}
@@ -44407,12 +44908,22 @@
return true;
}
if (constraintType.flags & 262144 /* TypeParameter */) {
- // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type
- // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X.
+ // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
+ // parameter. First infer from 'keyof S' to K.
var savePriority = priority;
priority |= 4 /* MappedTypeConstraint */;
inferFromTypes(getIndexType(source), constraintType);
priority = savePriority;
+ // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
+ // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
+ // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
+ // Pick<T, K>.
+ var extendedConstraint = getConstraintOfType(constraintType);
+ if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
+ return true;
+ }
+ // If no inferences can be made to K's constraint, infer from a union of the property types
+ // in the source to the template type X.
var valueTypes = ts.compact([
getIndexTypeOfType(source, 0 /* String */),
getIndexTypeOfType(source, 1 /* Number */)
@@ -44431,7 +44942,7 @@
}
if (ts.getObjectFlags(target) & 32 /* Mapped */) {
var constraintType = getConstraintTypeFromMappedType(target);
- if (inferFromMappedTypeConstraint(source, target, constraintType)) {
+ if (inferToMappedType(source, target, constraintType)) {
return;
}
}
@@ -44444,11 +44955,11 @@
}
}
function inferFromProperties(source, target) {
- if (isTupleType(source)) {
+ if (isArrayType(source) || isTupleType(source)) {
if (isTupleType(target)) {
- var sourceLength = getLengthOfTupleType(source);
+ var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0;
var targetLength = getLengthOfTupleType(target);
- var sourceRestType = getRestTypeOfTupleType(source);
+ var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source);
var targetRestType = getRestTypeOfTupleType(target);
var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
for (var i = 0; i < fixedLength; i++) {
@@ -44471,8 +44982,8 @@
}
}
var properties = getPropertiesOfObjectType(target);
- for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
- var targetProp = properties_5[_i];
+ for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) {
+ var targetProp = properties_4[_i];
var sourceProp = getPropertyOfType(source, targetProp.escapedName);
if (sourceProp) {
inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
@@ -44485,7 +44996,7 @@
var sourceLen = sourceSignatures.length;
var targetLen = targetSignatures.length;
var len = sourceLen < targetLen ? sourceLen : targetLen;
- var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */);
+ var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */);
for (var i = 0; i < len; i++) {
inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters);
}
@@ -44496,17 +45007,10 @@
var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
// Once we descend into a bivariant signature we remain bivariant for all nested inferences
bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */;
- forEachMatchingParameterType(source, target, inferFromContravariantTypes);
+ applyToParameterTypes(source, target, inferFromContravariantTypes);
bivariant = saveBivariant;
}
- var sourceTypePredicate = getTypePredicateOfSignature(source);
- var targetTypePredicate = getTypePredicateOfSignature(target);
- if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) {
- inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type);
- }
- else {
- inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
- }
+ applyToReturnTypes(source, target, inferFromTypes);
}
function inferFromIndexTypes(source, target) {
var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
@@ -44529,8 +45033,8 @@
}
}
function typeIdenticalToSomeType(type, types) {
- for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
- var t = types_10[_i];
+ for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
+ var t = types_11[_i];
if (isTypeIdenticalTo(t, type)) {
return true;
}
@@ -44623,7 +45127,7 @@
if (defaultType) {
// Instantiate the default type. Any forward reference to a type
// parameter should be instantiated to the empty object type.
- inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context));
+ inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
}
else {
inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
@@ -44636,7 +45140,7 @@
inference.inferredType = inferredType;
var constraint = getConstraintOfTypeParameter(inference.typeParameter);
if (constraint) {
- var instantiatedConstraint = instantiateType(constraint, context);
+ var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
inference.inferredType = inferredType = instantiatedConstraint;
}
@@ -44661,17 +45165,23 @@
case "console":
return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
case "$":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
case "describe":
case "suite":
case "it":
case "test":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha;
case "process":
case "require":
case "Buffer":
case "module":
- return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig;
+ return compilerOptions.types
+ ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig
+ : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
case "Map":
case "Set":
case "Promise":
@@ -44807,9 +45317,8 @@
}
return false;
}
- function hasNarrowableDeclaredType(expr) {
- var type = getDeclaredTypeOfReference(expr);
- return !!(type && type.flags & 1048576 /* Union */);
+ function isSyntheticThisPropertyAccess(expr) {
+ return ts.isAccessExpression(expr) && expr.expression.kind === 100 /* ThisKeyword */ && !!(expr.expression.flags & 8 /* Synthesized */);
}
function findDiscriminantProperties(sourceProperties, target) {
var result;
@@ -44886,8 +45395,8 @@
}
function getTypeFactsOfTypes(types) {
var result = 0 /* None */;
- for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
- var t = types_11[_i];
+ for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
+ var t = types_12[_i];
result |= getTypeFacts(t);
}
return result;
@@ -45167,7 +45676,7 @@
if (type.flags & 1048576 /* Union */) {
var types = type.types;
var filtered = ts.filter(types, f);
- return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly);
+ return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
}
return f(type) ? type : neverType;
}
@@ -45181,8 +45690,8 @@
var types = type.types;
var mappedType;
var mappedTypes;
- for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
- var current = types_12[_i];
+ for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
+ var current = types_13[_i];
var t = mapper(current);
if (t) {
if (!mappedType) {
@@ -45264,8 +45773,8 @@
}
function isEvolvingArrayTypeList(types) {
var hasEvolvingArrayType = false;
- for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
- var t = types_13[_i];
+ for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
+ var t = types_14[_i];
if (!(t.flags & 131072 /* Never */)) {
if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
return false;
@@ -45763,6 +46272,15 @@
assumeTrue = !assumeTrue;
}
var valueType = getTypeOfExpression(value);
+ if ((type.flags & 2 /* Unknown */) && (operator === 35 /* EqualsEqualsEqualsToken */) && assumeTrue) {
+ if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
+ return valueType;
+ }
+ if (valueType.flags & 524288 /* Object */) {
+ return nonPrimitiveType;
+ }
+ return type;
+ }
if (valueType.flags & 98304 /* Nullable */) {
if (!strictNullChecks) {
return type;
@@ -45792,9 +46310,9 @@
// We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands
var target = getReferenceCandidate(typeOfExpr.expression);
if (!isMatchingReference(reference, target)) {
- // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a
- // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type.
- if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) {
+ // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the
+ // narrowed type of 'y' to its declared type.
+ if (containsMatchingReference(reference, target)) {
return declaredType;
}
return type;
@@ -45835,13 +46353,37 @@
}
}
function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
- // We only narrow if all case expressions specify values with unit types
+ // We only narrow if all case expressions specify
+ // values with unit types, except for the case where
+ // `type` is unknown. In this instance we map object
+ // types to the nonPrimitive type and narrow with that.
var switchTypes = getSwitchClauseTypes(switchStatement);
if (!switchTypes.length) {
return type;
}
var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
+ if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
+ var groundClauseTypes = void 0;
+ for (var i = 0; i < clauseTypes.length; i += 1) {
+ var t = clauseTypes[i];
+ if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
+ if (groundClauseTypes !== undefined) {
+ groundClauseTypes.push(t);
+ }
+ }
+ else if (t.flags & 524288 /* Object */) {
+ if (groundClauseTypes === undefined) {
+ groundClauseTypes = clauseTypes.slice(0, i);
+ }
+ groundClauseTypes.push(nonPrimitiveType);
+ }
+ else {
+ return type;
+ }
+ }
+ return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
+ }
var discriminantType = getUnionType(clauseTypes);
var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
@@ -45942,9 +46484,14 @@
function narrowTypeByInstanceof(type, expr, assumeTrue) {
var left = getReferenceCandidate(expr.left);
if (!isMatchingReference(reference, left)) {
- // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an
- // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type.
- if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) {
+ // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the
+ // narrowed type of 'y' to its declared type. We do this because preceding 'x.y'
+ // references might reference a different 'y' property. However, we make an exception
+ // for property accesses where x is a synthetic 'this' expression, indicating that we
+ // were called from isPropertyInitializedInConstructor. Without this exception,
+ // initializations of 'this' properties that occur before a 'this instanceof XXX'
+ // check would not be considered.
+ if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) {
return declaredType;
}
return type;
@@ -46011,7 +46558,7 @@
return type;
}
if (ts.isIdentifierTypePredicate(predicate)) {
- var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)];
+ var predicateArgument = callExpression.arguments[predicate.parameterIndex];
if (predicateArgument) {
if (isMatchingReference(reference, predicateArgument)) {
return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
@@ -46088,7 +46635,7 @@
return ts.findAncestor(node.parent, function (node) {
return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
node.kind === 245 /* ModuleBlock */ ||
- node.kind === 279 /* SourceFile */ ||
+ node.kind === 284 /* SourceFile */ ||
node.kind === 154 /* PropertyDeclaration */;
});
}
@@ -46209,7 +46756,7 @@
// 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 !== 279 /* SourceFile */) {
+ while (container.kind !== 284 /* SourceFile */) {
if (container.parent === declaration) {
if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
@@ -46315,6 +46862,7 @@
function checkNestedBlockScopedBinding(node, symbol) {
if (languageVersion >= 2 /* ES2015 */ ||
(symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
+ ts.isSourceFile(symbol.valueDeclaration) ||
symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) {
return;
}
@@ -46502,22 +47050,27 @@
if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
captureLexicalThis(node, container);
}
- var type = tryGetThisTypeAt(node, container);
- if (!type && noImplicitThis) {
+ var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
+ if (noImplicitThis) {
+ var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
+ if (type === globalThisType_1 && capturedByArrowFunction) {
+ error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
+ }
+ else if (!type) {
// With noImplicitThis, functions may not reference 'this' if it has type 'any'
- var diag = error(node, capturedByArrowFunction && container.kind === 279 /* 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);
+ var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
if (!ts.isSourceFile(container)) {
var outsideThis = tryGetThisTypeAt(container);
- if (outsideThis) {
- addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
+ if (outsideThis && outsideThis !== globalThisType_1) {
+ ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
+ }
}
}
}
return type || anyType;
}
- function tryGetThisTypeAt(node, container) {
+ function tryGetThisTypeAt(node, includeGlobalThis, container) {
+ if (includeGlobalThis === void 0) { includeGlobalThis = true; }
if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
var isInJS = ts.isInJSFile(node);
if (ts.isFunctionLike(container) &&
@@ -46562,6 +47115,16 @@
return getFlowTypeOfReference(node, type);
}
}
+ if (ts.isSourceFile(container)) {
+ // look up in the source file's locals or exports
+ if (container.commonJsModuleIndicator) {
+ var fileSymbol = getSymbolOfNode(container);
+ return fileSymbol && getTypeOfSymbol(fileSymbol);
+ }
+ else if (includeGlobalThis) {
+ return getTypeOfSymbol(globalThisSymbol);
+ }
+ }
}
function getClassNameFromPrototypeMethod(container) {
// Check if it's the RHS of a x.prototype.y = function [name]() { .... }
@@ -46617,7 +47180,7 @@
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 294 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -46631,7 +47194,7 @@
}
}
function isInConstructorArgumentInitializer(node, constructorDecl) {
- return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; });
+ return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 151 /* Parameter */ && n.parent === constructorDecl; });
}
function checkSuperExpression(node) {
var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node;
@@ -46856,7 +47419,7 @@
while (type) {
var thisType = getThisTypeFromContextualType(type);
if (thisType) {
- return instantiateType(thisType, getContextualMapper(containingLiteral));
+ return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
}
if (literal.parent.kind !== 275 /* PropertyAssignment */) {
break;
@@ -47151,7 +47714,15 @@
}
function getTypeOfPropertyOfContextualType(type, name) {
return mapType(type, function (t) {
- if (t.flags & 3670016 /* StructuredType */) {
+ if (isGenericMappedType(t)) {
+ var constraint = getConstraintTypeFromMappedType(t);
+ var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
+ var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
+ if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
+ return substituteIndexedMappedType(t, propertyNameType);
+ }
+ }
+ else if (t.flags & 3670016 /* StructuredType */) {
var prop = getPropertyOfType(t, name);
if (prop) {
return getTypeOfSymbol(prop);
@@ -47287,18 +47858,46 @@
// Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
// be "pushed" onto a node using the contextualType property.
function getApparentTypeOfContextualType(node) {
- var contextualType = getContextualType(node);
- contextualType = contextualType && mapType(contextualType, getApparentType);
- if (contextualType && contextualType.flags & 1048576 /* Union */) {
+ var contextualType = instantiateContextualType(getContextualType(node), node);
+ if (contextualType) {
+ var apparentType = mapType(contextualType, getApparentType, /*noReductions*/ true);
+ if (apparentType.flags & 1048576 /* Union */) {
if (ts.isObjectLiteralExpression(node)) {
- return discriminateContextualTypeByObjectMembers(node, contextualType);
+ return discriminateContextualTypeByObjectMembers(node, apparentType);
}
else if (ts.isJsxAttributes(node)) {
- return discriminateContextualTypeByJSXAttributes(node, contextualType);
+ return discriminateContextualTypeByJSXAttributes(node, apparentType);
+ }
+ }
+ return apparentType;
+ }
+ }
+ // If the given contextual type contains instantiable types and if a mapper representing
+ // return type inferences is available, instantiate those types using that mapper.
+ function instantiateContextualType(contextualType, node) {
+ if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) {
+ var inferenceContext = getInferenceContext(node);
+ if (inferenceContext && inferenceContext.returnMapper) {
+ return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
}
}
return contextualType;
}
+ // This function is similar to instantiateType, except that (a) it only instantiates types that
+ // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
+ // no reductions on instantiated union types.
+ function instantiateInstantiableTypes(type, mapper) {
+ if (type.flags & 63176704 /* Instantiable */) {
+ return instantiateType(type, mapper);
+ }
+ if (type.flags & 1048576 /* Union */) {
+ return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
+ }
+ if (type.flags & 2097152 /* Intersection */) {
+ return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
+ }
+ return type;
+ }
/**
* Woah! Do you really want to use this function?
*
@@ -47344,7 +47943,7 @@
return getContextualTypeForArgument(parent, node);
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- return getTypeFromTypeNode(parent.type);
+ return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type);
case 204 /* BinaryExpression */:
return getContextualTypeForBinaryOperand(node);
case 275 /* PropertyAssignment */:
@@ -47378,9 +47977,9 @@
}
return undefined;
}
- function getContextualMapper(node) {
- var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; });
- return ancestor ? ancestor.contextualMapper : identityMapper;
+ function getInferenceContext(node) {
+ var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
+ return ancestor && ancestor.inferenceContext;
}
function getContextualJsxElementAttributesType(node) {
if (ts.isJsxOpeningElement(node) && node.parent.contextualType) {
@@ -47561,8 +48160,8 @@
}
var signatureList;
var types = type.types;
- for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
- var current = types_14[_i];
+ for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
+ var current = types_15[_i];
var signature = getContextualCallSignature(current, node);
if (signature) {
if (!signatureList) {
@@ -47580,12 +48179,7 @@
}
}
// Result is union of signatures collected (return type is union of return types of this signature set)
- var result;
- if (signatureList) {
- result = cloneSignature(signatureList[0]);
- result.unionSignatures = signatureList;
- }
- return result;
+ return signatureList && createUnionSignature(signatureList[0], signatureList);
}
function checkSpreadExpression(node, checkMode) {
if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
@@ -47605,6 +48199,7 @@
var elementTypes = [];
var inDestructuringPattern = ts.isAssignmentTarget(node);
var contextualType = getApparentTypeOfContextualType(node);
+ var inConstContext = isConstContext(node);
for (var index = 0; index < elementCount; index++) {
var e = elements[index];
if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) {
@@ -47647,21 +48242,24 @@
type.pattern = node;
return type;
}
- else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) {
+ else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, inConstContext)) {
return tupleResult;
}
else if (forceTuple) {
return createTupleType(elementTypes, minLength, hasRestElement);
}
}
- return getArrayLiteralType(elementTypes, 2 /* Subtype */);
+ return createArrayType(elementTypes.length ?
+ getUnionType(elementTypes, 2 /* Subtype */) :
+ strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext);
}
- function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) {
+ function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) {
if (elementCount === void 0) { elementCount = elementTypes.length; }
+ if (readonly === void 0) { readonly = false; }
// Infer a tuple type when the contextual type is or contains a tuple-like type
- if (contextualType && forEachType(contextualType, isTupleLikeType)) {
+ if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) {
var minLength = elementCount - (hasRestElement ? 1 : 0);
- var pattern = contextualType.pattern;
+ var pattern = contextualType && 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 (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) {
@@ -47679,14 +48277,8 @@
}
}
}
- return createTupleType(elementTypes, minLength, hasRestElement);
- }
+ return createTupleType(elementTypes, minLength, hasRestElement, readonly);
}
- function getArrayLiteralType(elementTypes, unionReduction) {
- if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
- return createArrayType(elementTypes.length ?
- getUnionType(elementTypes, unionReduction) :
- strictNullChecks ? implicitNeverType : undefinedWideningType);
}
function isNumericName(name) {
switch (name.kind) {
@@ -47750,15 +48342,15 @@
}
return links.resolvedType;
}
- function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) {
+ function getObjectLiteralIndexInfo(node, offset, properties, kind) {
var propTypes = [];
for (var i = 0; i < properties.length; i++) {
- if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) {
+ if (kind === 0 /* String */ || isNumericName(node.properties[i + offset].name)) {
propTypes.push(getTypeOfSymbol(properties[i]));
}
}
var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
- return createIndexInfo(unionType, /*isReadonly*/ false);
+ return createIndexInfo(unionType, isConstContext(node));
}
function getImmediateAliasedSymbol(symbol) {
ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
@@ -47778,14 +48370,15 @@
var propertiesTable;
var propertiesArray = [];
var spread = emptyObjectType;
- var propagatedFlags = 0;
var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */);
+ var inConstContext = isConstContext(node);
+ var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
var enumTag = ts.getJSDocEnumTag(node);
var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
- var typeFlags = 0;
+ var objectFlags = freshObjectLiteralFlag;
var patternWithComputedProperties = false;
var hasComputedStringProperty = false;
var hasComputedNumberProperty = false;
@@ -47812,11 +48405,11 @@
checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
}
}
- typeFlags |= type.flags;
+ objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */;
var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
var prop = nameType ?
- createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), 2048 /* Late */) :
- createSymbol(4 /* Property */ | member.flags, member.escapedName);
+ createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 2048 /* Late */) :
+ createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
if (nameType) {
prop.nameType = nameType;
}
@@ -47854,19 +48447,18 @@
checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
}
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
propertiesArray = [];
propertiesTable = ts.createSymbolTable();
hasComputedStringProperty = false;
hasComputedNumberProperty = false;
- typeFlags = 0;
}
var type = checkExpression(memberDecl.expression);
if (!isValidSpreadType(type)) {
error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
return errorType;
}
- spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
offset = i + 1;
continue;
}
@@ -47913,17 +48505,16 @@
}
if (spread !== emptyObjectType) {
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */);
+ spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
}
return spread;
}
return createObjectLiteralType();
function createObjectLiteralType() {
- var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined;
- var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined;
+ var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
+ var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
- result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */;
- result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag;
+ result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
if (isJSObjectLiteral) {
result.objectFlags |= 16384 /* JSLiteral */;
}
@@ -47933,7 +48524,6 @@
if (inDestructuringPattern) {
result.pattern = node;
}
- propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */;
return result;
}
}
@@ -48009,7 +48599,6 @@
var hasSpreadAnyType = false;
var typeToIntersect;
var explicitlySpecifyChildrenAttribute = false;
- var typeFlags = 0;
var objectFlags = 4096 /* JsxAttributes */;
var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
@@ -48017,7 +48606,7 @@
var member = attributeDecl.symbol;
if (ts.isJsxAttribute(attributeDecl)) {
var exprType = checkJsxAttribute(attributeDecl, checkMode);
- typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */;
+ objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */;
var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
attributeSymbol.declarations = member.declarations;
attributeSymbol.parent = member.parent;
@@ -48034,7 +48623,7 @@
else {
ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */);
if (attributesTable.size > 0) {
- spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
attributesTable = ts.createSymbolTable();
}
var exprType = checkExpressionCached(attributeDecl.expression, checkMode);
@@ -48042,7 +48631,7 @@
hasSpreadAnyType = true;
}
if (isValidSpreadType(exprType)) {
- spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
}
else {
typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
@@ -48051,7 +48640,7 @@
}
if (!hasSpreadAnyType) {
if (attributesTable.size > 0) {
- spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
}
}
// Handle children attribute
@@ -48079,7 +48668,7 @@
childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
var childPropMap = ts.createSymbolTable();
childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
- spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags);
+ spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
}
}
if (hasSpreadAnyType) {
@@ -48097,8 +48686,7 @@
function createJsxAttributesType() {
objectFlags |= freshObjectLiteralFlag;
var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
- result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags;
- result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags;
+ result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */;
return result;
}
}
@@ -48109,7 +48697,7 @@
// In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
// because then type of children property will have constituent of string type.
if (child.kind === 11 /* JsxText */) {
- if (!child.containsOnlyWhiteSpaces) {
+ if (!child.containsOnlyTriviaWhiteSpaces) {
childrenTypes.push(stringType);
}
}
@@ -48180,7 +48768,7 @@
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 */);
+ var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
if (candidate) {
if (links) {
links.jsxNamespace = candidate;
@@ -48385,7 +48973,7 @@
// Mark local symbol as referenced here because it might not have been marked
// if jsx emit was not react as there wont be error being emitted
reactSym.isReferenced = 67108863 /* All */;
- // If react symbol is alias, mark it as refereced
+ // If react symbol is alias, mark it as referenced
if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) {
markAliasSymbolAsReferenced(reactSym);
}
@@ -48623,6 +49211,15 @@
if (isJSLiteralType(leftType)) {
return anyType;
}
+ if (leftType.symbol === globalThisSymbol) {
+ if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
+ error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
+ }
+ else if (noImplicitAny) {
+ error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
+ }
+ return anyType;
+ }
if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType);
}
@@ -48701,7 +49298,7 @@
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));
+ ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
}
}
function isInPropertyInitializer(node) {
@@ -48710,7 +49307,19 @@
case 154 /* PropertyDeclaration */:
return true;
case 275 /* PropertyAssignment */:
- // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`.
+ case 156 /* MethodDeclaration */:
+ case 158 /* GetAccessor */:
+ case 159 /* SetAccessor */:
+ case 277 /* SpreadAssignment */:
+ case 149 /* ComputedPropertyName */:
+ case 216 /* TemplateSpan */:
+ case 270 /* JsxExpression */:
+ case 267 /* JsxAttribute */:
+ case 268 /* JsxAttributes */:
+ case 269 /* JsxSpreadAttribute */:
+ case 262 /* JsxOpeningElement */:
+ case 211 /* ExpressionWithTypeArguments */:
+ case 273 /* HeritageClause */:
return false;
default:
return ts.isExpressionNode(node) ? false : "quit";
@@ -48778,7 +49387,7 @@
}
var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
if (relatedInfo) {
- addRelatedInfo(resultDiagnostic, relatedInfo);
+ ts.addRelatedInfo(resultDiagnostic, relatedInfo);
}
diagnostics.add(resultDiagnostic);
}
@@ -49177,38 +49786,34 @@
return undefined;
}
// 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) {
+ function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
- var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature;
- forEachMatchingParameterType(sourceSignature, signature, function (source, target) {
+ // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
+ // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
+ // for T but leave it possible to later infer '[any]' back to A.
+ var restType = getEffectiveRestType(contextualSignature);
+ var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
+ var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
+ applyToParameterTypes(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, source, target);
});
- if (!contextualMapper) {
- inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */);
+ if (!inferenceContext) {
+ applyToReturnTypes(contextualSignature, signature, function (source, target) {
+ inferTypes(context.inferences, source, target, 8 /* ReturnType */);
+ });
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
}
- function inferJsxTypeArguments(node, signature, excludeArgument, context) {
+ function inferJsxTypeArguments(node, signature, checkMode, context) {
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context);
+ var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
inferTypes(context.inferences, checkAttrType, paramType);
return getInferredTypes(context);
}
- function inferTypeArguments(node, signature, args, excludeArgument, context) {
- // Clear out all the inference results from the last time inferTypeArguments was called on this context
- for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) {
- var inference = _a[_i];
- // As an optimization, we don't have to clear (and later recompute) inferred types
- // for type parameters that have already been fixed on the previous call to inferTypeArguments.
- // It would be just as correct to reset all of them. But then we'd be repeating the same work
- // for the type parameters that were fixed, namely the work done by getInferredType.
- if (!inference.isFixed) {
- inference.inferredType = undefined;
- }
- }
+ function inferTypeArguments(node, signature, args, checkMode, context) {
if (ts.isJsxOpeningLikeElement(node)) {
- return inferJsxTypeArguments(node, signature, excludeArgument, context);
+ return inferJsxTypeArguments(node, signature, checkMode, context);
}
// If a contextual type is available, infer from that type to the return type of the call expression. For
// example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
@@ -49217,10 +49822,11 @@
if (node.kind !== 152 /* Decorator */) {
var contextualType = getContextualType(node);
if (contextualType) {
- // We clone the contextual mapper to avoid disturbing a resolution in progress for an
+ // We clone the inference context to avoid disturbing a resolution in progress for an
// outer call expression. Effectively we just want a snapshot of whatever has been
// inferred for any outer call expression so far.
- var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node)));
+ var outerMapper = getMapperFromContext(cloneInferenceContext(getInferenceContext(node), 1 /* NoDefault */));
+ var instantiatedType = instantiateType(contextualType, outerMapper);
// If the contextual type is a generic function type with a single call signature, we
// instantiate the type with its own type parameters and type arguments. This ensures that
// the type parameters are not erased to type any during type inference such that they can
@@ -49235,6 +49841,9 @@
var inferenceTargetType = getReturnTypeOfSignature(signature);
// Inferences made from return types have lower priority than all other inferences.
inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */);
+ // Create a type mapper for instantiating generic contextual types using the inferences made
+ // from the return type.
+ context.returnMapper = getMapperFromContext(cloneInferredPartOfContext(context));
}
}
var thisType = getThisTypeOfSignature(signature);
@@ -49249,10 +49858,7 @@
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- // For context sensitive arguments we pass the identityMapper, which is a signal to treat all
- // context sensitive function expressions as wildcards
- var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
- var argType = checkExpressionWithContextualType(arg, paramType, mapper);
+ var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
inferTypes(context.inferences, argType, paramType);
}
}
@@ -49276,7 +49882,7 @@
// and the argument are ...x forms.
return arg.kind === 215 /* SyntheticExpression */ ?
createArrayType(arg.type) :
- getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context));
+ getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
}
}
var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType;
@@ -49284,7 +49890,7 @@
var types = [];
var spreadIndex = -1;
for (var i = index; i < argCount; i++) {
- var argType = checkExpressionWithContextualType(args[i], contextualType, context);
+ var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
if (spreadIndex < 0 && isSpreadArgument(args[i])) {
spreadIndex = i - index;
}
@@ -49334,19 +49940,18 @@
* @param node a JSX opening-like element we are trying to figure its call signature
* @param signature a candidate signature we are trying whether it is a call signature
* @param relation a relationship to check parameter and argument type
- * @param excludeArgument
*/
- function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors) {
// Stateless function components can have maximum of three arguments: "props", "context", and "updater".
// However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
// can be specified by users through attributes property.
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined);
+ var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes);
}
- function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignature(node, args, signature, relation, checkMode, reportErrors) {
if (ts.isJsxOpeningLikeElement(node)) {
- return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors);
+ return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors);
}
var thisType = getThisTypeOfSignature(signature);
if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) {
@@ -49368,11 +49973,11 @@
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
- // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter),
+ var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
+ // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
// 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;
+ var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
return false;
}
@@ -49529,25 +50134,41 @@
if (argCount <= max && hasSpreadArgument) {
argCount--;
}
+ var spanArray;
var related;
+ var error = hasRestParameter || hasSpreadArgument ? 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 : ts.Diagnostics.Expected_0_arguments_but_got_1;
if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
if (paramDecl) {
related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined);
}
}
- 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;
- var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount);
- return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1;
- }
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);
}
- var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount);
- return related ? addRelatedInfo(diagnostic, related) : diagnostic;
+ if (!hasSpreadArgument && argCount < min) {
+ var diagnostic_1 = ts.createDiagnosticForNode(node, error, paramRange, argCount);
+ return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
+ }
+ if (hasRestParameter || hasSpreadArgument) {
+ spanArray = ts.createNodeArray(args);
+ if (hasSpreadArgument && argCount) {
+ var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
+ spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
+ }
+ }
+ else {
+ spanArray = ts.createNodeArray(args.slice(max));
+ }
+ spanArray.pos = ts.first(spanArray).pos;
+ spanArray.end = ts.last(spanArray).end;
+ if (spanArray.end === spanArray.pos) {
+ spanArray.end++;
+ }
+ var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
+ return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
}
function getTypeArgumentArityError(node, signatures, typeArguments) {
var argCount = typeArguments.length;
@@ -49577,7 +50198,7 @@
}
return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
}
- function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) {
+ function resolveCall(node, signatures, candidatesOutArray, checkMode, fallbackError) {
var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */;
var isDecorator = node.kind === 152 /* Decorator */;
var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
@@ -49613,7 +50234,7 @@
// For a decorator, no arguments are susceptible to contextual typing due to the fact
// decorators are applied to a declaration by the emitter, and not to an expression.
var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
- var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined;
+ var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
// The following variables are captured and modified by calls to chooseOverload.
// If overload resolution or type argument inference fails, we want to report the
// best error possible. The best error is one which says that an argument was not
@@ -49641,7 +50262,7 @@
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 = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
+ var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 191 /* 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
@@ -49667,12 +50288,7 @@
// skip the checkApplicableSignature check.
if (reportErrors) {
if (candidateForArgumentError) {
- // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...]
- // The importance of excludeArgument is to prevent us from typing function expression parameters
- // in arguments too early. If possible, we'd like to only type them once we know the correct
- // overload. However, this matters for the case where the call is correct. When the call is
- // 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);
+ checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, 0 /* Normal */, /*reportErrors*/ true);
}
else if (candidateForArgumentArityError) {
diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
@@ -49704,7 +50320,7 @@
if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
return undefined;
}
- if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false)) {
candidateForArgumentError = candidate;
return undefined;
}
@@ -49728,9 +50344,10 @@
}
else {
inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
+ typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
+ argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
}
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// 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 (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -49741,21 +50358,21 @@
else {
checkCandidate = candidate;
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
}
continue;
}
- if (excludeArgument) {
+ if (argCheckMode) {
// If one or more context sensitive arguments were excluded, we start including
// them now (and keeping do so for any subsequent candidates) and perform a second
// round of type inference and applicability checking for this particular candidate.
- excludeArgument = undefined;
+ argCheckMode = 0 /* Normal */;
if (inferenceContext) {
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// 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 (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -49763,7 +50380,7 @@
continue;
}
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
@@ -49777,20 +50394,6 @@
return undefined;
}
}
- function getExcludeArgument(args) {
- var excludeArgument;
- // We do not need to call `getEffectiveArgumentCount` here as it only
- // applies when calculating the number of arguments for a decorator.
- for (var i = 0; i < args.length; i++) {
- if (isContextSensitive(args[i])) {
- if (!excludeArgument) {
- excludeArgument = new Array(args.length);
- }
- excludeArgument[i] = true;
- }
- }
- return excludeArgument;
- }
// 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) {
@@ -49879,7 +50482,7 @@
}
function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext);
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
return createSignatureInstantiation(candidate, typeArgumentTypes);
}
function getLongestCandidateIndex(candidates, argsCount) {
@@ -49898,7 +50501,7 @@
}
return maxParamsIndex;
}
- function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveCallExpression(node, candidatesOutArray, checkMode) {
if (node.expression.kind === 98 /* SuperKeyword */) {
var superType = checkSuperExpression(node.expression);
if (isTypeAny(superType)) {
@@ -49914,7 +50517,7 @@
var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
if (baseTypeNode) {
var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
- return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, baseConstructors, candidatesOutArray, checkMode);
}
}
return resolveUntypedCall(node);
@@ -49964,12 +50567,31 @@
}
return resolveErrorCall(node);
}
+ // When a call to a generic function is an argument to an outer call to a generic function for which
+ // inference is in process, we have a choice to make. If the inner call relies on inferences made from
+ // its contextual type to its return type, deferring the inner call processing allows the best possible
+ // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
+ // the inner call, the inner call should be processed early. There's no sure way to know which choice is
+ // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
+ // If no type arguments are specified in the inner call and at least one call signature is generic and
+ // returns a function type, we choose to defer processing. This narrowly permits function composition
+ // operators to flow inferences through return types, but otherwise processes calls right away. We
+ // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
+ // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
+ // from which we never make inferences).
+ if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
+ skippedGenericFunction(node, checkMode);
+ return resolvingSignature;
+ }
// If the function is explicitly marked with `@class`, then it must be constructed.
if (callSignatures.some(function (sig) { return ts.isInJSFile(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);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
+ }
+ function isGenericFunctionReturningFunction(signature) {
+ return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
}
/**
* TS 1.0 spec: 4.12
@@ -49981,7 +50603,7 @@
return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
!numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
}
- function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveNewExpression(node, candidatesOutArray, checkMode) {
if (node.arguments && languageVersion < 1 /* ES5 */) {
var spreadIndex = getSpreadArgumentIndex(node.arguments);
if (spreadIndex >= 0) {
@@ -50029,7 +50651,7 @@
error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
return resolveErrorCall(node);
}
- return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, constructSignatures, candidatesOutArray, checkMode);
}
// 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
@@ -50037,7 +50659,7 @@
// 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, isForSignatureHelp);
+ var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode);
if (!noImplicitAny) {
if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
@@ -50059,13 +50681,12 @@
var firstBase = baseTypes[0];
if (firstBase.flags & 2097152 /* Intersection */) {
var types = firstBase.types;
- var mixinCount = ts.countWhere(types, isMixinConstructorType);
+ var mixinFlags = findMixins(types);
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 (!mixinFlags[i]) {
if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
if (intersectionMember.symbol === target) {
return true;
@@ -50075,6 +50696,7 @@
}
}
}
+ i++;
}
return false;
}
@@ -50118,7 +50740,7 @@
var diagnostic = 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, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
+ invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
}
function invocationErrorRecovery(apparentType, kind, diagnostic) {
if (!apparentType.symbol) {
@@ -50131,10 +50753,10 @@
var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
if (!sigs || !sigs.length)
return;
- 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));
+ 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, isForSignatureHelp) {
+ function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
var tagType = checkExpression(node.tag);
var apparentType = getApparentType(tagType);
if (apparentType === errorType) {
@@ -50150,7 +50772,7 @@
invocationError(node, apparentType, 0 /* Call */);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
}
/**
* Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
@@ -50175,7 +50797,7 @@
/**
* Resolves a decorator as if it were a call expression.
*/
- function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveDecorator(node, candidatesOutArray, checkMode) {
var funcType = checkExpression(node.expression);
var apparentType = getApparentType(funcType);
if (apparentType === errorType) {
@@ -50200,7 +50822,7 @@
invocationErrorRecovery(apparentType, 0 /* Call */, diag);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode, headMessage);
}
function createSignatureForJSXIntrinsic(node, result) {
var namespace = getJsxNamespaceAt(node);
@@ -50219,11 +50841,11 @@
/*hasRestparameter*/ false,
/*hasLiteralTypes*/ false);
}
- function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
var fakeSignature = createSignatureForJSXIntrinsic(node, result);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes);
+ checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
return fakeSignature;
}
var exprTypes = checkExpression(node.tagName);
@@ -50240,7 +50862,7 @@
error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
return resolveErrorCall(node);
}
- return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, signatures, candidatesOutArray, checkMode);
}
/**
* Sometimes, we have a decorator that could accept zero arguments,
@@ -50254,19 +50876,19 @@
signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
});
}
- function resolveSignature(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveSignature(node, candidatesOutArray, checkMode) {
switch (node.kind) {
case 191 /* CallExpression */:
- return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveCallExpression(node, candidatesOutArray, checkMode);
case 192 /* NewExpression */:
- return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveNewExpression(node, candidatesOutArray, checkMode);
case 193 /* TaggedTemplateExpression */:
- return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
case 152 /* Decorator */:
- return resolveDecorator(node, candidatesOutArray, isForSignatureHelp);
+ return resolveDecorator(node, candidatesOutArray, checkMode);
case 262 /* JsxOpeningElement */:
case 261 /* JsxSelfClosingElement */:
- return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp);
+ return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
}
throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
}
@@ -50277,8 +50899,7 @@
* 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, isForSignatureHelp) {
- if (isForSignatureHelp === void 0) { isForSignatureHelp = false; }
+ function getResolvedSignature(node, candidatesOutArray, checkMode) {
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,
@@ -50289,11 +50910,15 @@
return cached;
}
links.resolvedSignature = resolvingSignature;
- var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp);
+ var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
+ // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
+ // resolution should be deferred.
+ if (result !== resolvingSignature) {
// 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.
links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ }
return result;
}
/**
@@ -50369,10 +50994,15 @@
* @param node The call/new expression to be checked.
* @returns On success, the expression's signature's return type. On failure, anyType.
*/
- function checkCallExpression(node) {
+ function checkCallExpression(node, checkMode) {
if (!checkGrammarTypeArguments(node, node.typeArguments))
checkGrammarArguments(node.arguments);
- var signature = getResolvedSignature(node);
+ var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
+ if (signature === resolvingSignature) {
+ // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
+ // returns a function type. We defer checking and return nonInferrableType.
+ return nonInferrableType;
+ }
if (node.expression.kind === 98 /* SuperKeyword */) {
return voidType;
}
@@ -50472,7 +51102,7 @@
var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
anonymousSymbol.type = defaultContainingObject;
- synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0) : defaultContainingObject;
+ synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
}
else {
synthType.syntheticType = type;
@@ -50519,9 +51149,37 @@
function checkAssertion(node) {
return checkAssertionWorker(node, node.type, node.expression);
}
+ function isValidConstAssertionArgument(node) {
+ switch (node.kind) {
+ case 10 /* StringLiteral */:
+ case 14 /* NoSubstitutionTemplateLiteral */:
+ case 8 /* NumericLiteral */:
+ case 9 /* BigIntLiteral */:
+ case 102 /* TrueKeyword */:
+ case 87 /* FalseKeyword */:
+ case 187 /* ArrayLiteralExpression */:
+ case 188 /* ObjectLiteralExpression */:
+ return true;
+ case 195 /* ParenthesizedExpression */:
+ return isValidConstAssertionArgument(node.expression);
+ case 202 /* PrefixUnaryExpression */:
+ var op = node.operator;
+ var arg = node.operand;
+ return op === 39 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
+ op === 38 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
+ }
+ return false;
+ }
function checkAssertionWorker(errNode, type, expression, checkMode) {
- var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode)));
+ var exprType = checkExpression(expression, checkMode);
+ if (ts.isConstTypeReference(type)) {
+ if (!isValidConstAssertionArgument(expression)) {
+ error(expression, ts.Diagnostics.A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal);
+ }
+ return getRegularTypeOfLiteralType(exprType);
+ }
checkSourceElement(type);
+ exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
var targetType = getTypeFromTypeNode(type);
if (produceDiagnostics && targetType !== errorType) {
var widenedType = getWidenedType(exprType);
@@ -50560,7 +51218,7 @@
}
}
function checkImportMetaProperty(node) {
- if (languageVersion < 6 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) {
+ if (languageVersion < 7 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) {
error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options);
}
var file = ts.getSourceFileOfNode(node);
@@ -50588,7 +51246,7 @@
if (isTupleType(restType)) {
var associatedNames = restType.target.associatedNames;
var index = pos - paramCount;
- return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index;
+ return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
}
return restParameter.escapedName;
}
@@ -50601,33 +51259,37 @@
return getTypeOfParameter(signature.parameters[pos]);
}
if (signature.hasRestParameter) {
+ // We want to return the value undefined for an out of bounds parameter position,
+ // so we need to check bounds here before calling getIndexedAccessType (which
+ // otherwise would return the type 'undefined').
var restType = getTypeOfSymbol(signature.parameters[paramCount]);
- if (isTupleType(restType)) {
- if (pos - paramCount < getLengthOfTupleType(restType)) {
- return restType.typeArguments[pos - paramCount];
- }
- return getRestTypeOfTupleType(restType);
+ var index = pos - paramCount;
+ if (!isTupleType(restType) || restType.target.hasRestElement || index < (restType.typeArguments || ts.emptyArray).length) {
+ return getIndexedAccessType(restType, getLiteralType(index));
}
- return getIndexTypeOfType(restType, 1 /* Number */);
}
return undefined;
}
function getRestTypeAtPosition(source, pos) {
var paramCount = getParameterCount(source);
var restType = getEffectiveRestType(source);
- if (restType && pos === paramCount - 1) {
+ var nonRestCount = paramCount - (restType ? 1 : 0);
+ if (restType && pos === nonRestCount) {
return restType;
}
- var start = restType ? Math.min(pos, paramCount - 1) : pos;
var types = [];
var names = [];
- for (var i = start; i < paramCount; i++) {
+ for (var i = pos; i < nonRestCount; i++) {
types.push(getTypeAtPosition(source, i));
names.push(getParameterNameAtPosition(source, i));
}
+ if (restType) {
+ types.push(getIndexedAccessType(restType, numberType));
+ names.push(getParameterNameAtPosition(source, nonRestCount));
+ }
var minArgumentCount = getMinArgumentCount(source);
- var minLength = minArgumentCount < start ? 0 : minArgumentCount - start;
- return createTupleType(types, minLength, !!restType, names);
+ var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos;
+ return createTupleType(types, minLength, !!restType, /*readonly*/ false, names);
}
function getParameterCount(signature) {
var length = signature.parameters.length;
@@ -50675,16 +51337,27 @@
function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
}
- function inferFromAnnotatedParameters(signature, context, mapper) {
+ function inferFromAnnotatedParameters(signature, context, inferenceContext) {
var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
for (var i = 0; i < len; i++) {
var declaration = signature.parameters[i].valueDeclaration;
if (declaration.type) {
var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
if (typeNode) {
- inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
+ inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
+ }
}
}
+ var restType = getEffectiveRestType(context);
+ if (restType && restType.flags & 262144 /* TypeParameter */) {
+ // The contextual signature has a generic rest parameter. We first instantiate the contextual
+ // signature (without fixing type parameters) and assign types to contextually typed parameters.
+ var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
+ assignContextualParameterTypes(signature, instantiatedContext);
+ // We then infer from a tuple type representing the parameters that correspond to the contextual
+ // rest parameter.
+ var restPos = getParameterCount(context) - 1;
+ inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
}
}
function assignContextualParameterTypes(signature, context) {
@@ -50786,7 +51459,7 @@
var functionFlags = ts.getFunctionFlags(func);
var type;
if (func.body.kind !== 218 /* Block */) {
- type = checkExpressionCached(func.body, checkMode);
+ type = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -50964,7 +51637,7 @@
ts.forEachReturnStatement(func.body, function (returnStatement) {
var expr = returnStatement.expression;
if (expr) {
- var type = checkExpressionCached(expr, checkMode);
+ var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51057,7 +51730,7 @@
ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
checkNodeDeferred(node);
// The identityMapper object is used to indicate that function expressions are wildcards
- if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) {
+ if (checkMode && checkMode & 4 /* 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);
@@ -51067,7 +51740,7 @@
var returnType = getReturnTypeFromBody(node, checkMode);
var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
- returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */;
+ returnOnlyType.objectFlags |= 524288 /* NonInferrableType */;
return links_1.contextFreeType = returnOnlyType;
}
return anyFunctionType;
@@ -51093,12 +51766,12 @@
if (contextualSignature) {
var signature = getSignaturesOfType(type, 0 /* Call */)[0];
if (isContextSensitive(node)) {
- var contextualMapper = getContextualMapper(node);
- if (checkMode === 2 /* Inferential */) {
- inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper);
+ var inferenceContext = getInferenceContext(node);
+ if (checkMode && checkMode & 2 /* Inferential */) {
+ inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
}
- var instantiatedContextualSignature = contextualMapper === identityMapper ?
- contextualSignature : instantiateSignature(contextualSignature, contextualMapper);
+ var instantiatedContextualSignature = inferenceContext ?
+ instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
assignContextualParameterTypes(signature, instantiatedContextualSignature);
}
if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
@@ -51364,13 +52037,13 @@
// Return true if type might be of the given kind. A union or intersection type might be of a given
// kind if at least one constituent type is of the given kind.
function maybeTypeOfKind(type, kind) {
- if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) {
+ if (type.flags & kind & ~131072 /* GenericMappedType */ || kind & 131072 /* GenericMappedType */ && isGenericMappedType(type)) {
return true;
}
if (type.flags & 3145728 /* UnionOrIntersection */) {
var types = type.types;
- for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
- var t = types_15[_i];
+ for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
+ var t = types_16[_i];
if (maybeTypeOfKind(t, kind)) {
return true;
}
@@ -51449,8 +52122,8 @@
if (strictNullChecks && properties.length === 0) {
return checkNonNullType(sourceType, node);
}
- for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) {
- var p = properties_6[_i];
+ for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
+ var p = properties_5[_i];
checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties, rightIsThis);
}
return sourceType;
@@ -51474,7 +52147,7 @@
return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
}
else if (property.kind === 277 /* SpreadAssignment */) {
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(property, 4 /* Rest */);
}
var nonRestNames = [];
@@ -51969,7 +52642,7 @@
// Async generator functions prior to ESNext require the __await, __asyncDelegator,
// and __asyncValues helpers
if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ &&
- languageVersion < 6 /* ESNext */) {
+ languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */);
}
// Generator functions prior to ES2015 require the __values helper
@@ -52016,23 +52689,26 @@
}
return node;
}
- function checkExpressionWithContextualType(node, contextualType, contextualMapper) {
+ function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
var context = getContextNode(node);
var saveContextualType = context.contextualType;
- var saveContextualMapper = context.contextualMapper;
+ var saveInferenceContext = context.inferenceContext;
context.contextualType = contextualType;
- context.contextualMapper = contextualMapper;
- var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ :
- contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */;
- var result = checkExpression(node, checkMode);
+ context.inferenceContext = inferenceContext;
+ var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
+ // We strip literal freshness when an appropriate contextual type is present such that contextually typed
+ // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
+ // here would be to not mark contextually typed literals as fresh in the first place.
+ var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
+ getRegularTypeOfLiteralType(type) : type;
context.contextualType = saveContextualType;
- context.contextualMapper = saveContextualMapper;
+ context.inferenceContext = saveInferenceContext;
return result;
}
function checkExpressionCached(node, checkMode) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- if (checkMode) {
+ if (checkMode && checkMode !== 0 /* Normal */) {
return checkExpression(node, checkMode);
}
// When computing a type that we're going to cache, we need to ignore any ongoing control flow
@@ -52095,13 +52771,17 @@
}
return false;
}
- function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
- if (arguments.length === 2) {
- contextualType = getContextualType(node);
+ function isConstContext(node) {
+ var parent = node.parent;
+ return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
+ (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
+ (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
}
+ function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
var type = checkExpression(node, checkMode, forceTuple);
- return isTypeAssertion(node) ? type :
- getWidenedLiteralLikeTypeForContextualType(type, contextualType);
+ return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
+ isTypeAssertion(node) ? type :
+ getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
}
function checkPropertyAssignment(node, checkMode) {
// Do not use hasDynamicName here, because that returns false for well known symbols.
@@ -52125,20 +52805,129 @@
return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
}
function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
+ if (checkMode & 8 /* SkipGenericFunctions */) {
+ skippedGenericFunction(node, checkMode);
+ return anyFunctionType;
+ }
var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType));
if (contextualSignature && !contextualSignature.typeParameters) {
- return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node)));
+ var context = getInferenceContext(node);
+ // We have an expression that is an argument of a generic function for which we are performing
+ // type argument inference. The expression is of a function type with a single generic call
+ // signature and a contextual function type with a single non-generic call signature. Now check
+ // if the outer function returns a function type with a single non-generic call signature and
+ // if some of the outer function type parameters have no inferences so far. If so, we can
+ // potentially add inferred type parameters to the outer function return type.
+ var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature));
+ if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
+ // Instantiate the signature with its own type parameters as type arguments, possibly
+ // renaming the type parameters to ensure they have unique names.
+ var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
+ // Infer from the parameters of the instantiated signature to the parameters of the
+ // contextual signature starting with an empty set of inference candidates.
+ var inferences_2 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
+ applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
+ inferTypes(inferences_2, source, target, /*priority*/ 0, /*contravariant*/ true);
+ });
+ if (ts.some(inferences_2, hasInferenceCandidates)) {
+ // We have inference candidates, indicating that one or more type parameters are referenced
+ // in the parameter types of the contextual signature. Now also infer from the return type.
+ applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
+ inferTypes(inferences_2, source, target);
+ });
+ // If the type parameters for which we produced candidates do not have any inferences yet,
+ // we adopt the new inference candidates and add the type parameters of the expression type
+ // to the set of inferred type parameters for the outer function return type.
+ if (!hasOverlappingInferences(context.inferences, inferences_2)) {
+ mergeInferences(context.inferences, inferences_2);
+ context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
+ return getOrCreateTypeFromSignature(instantiatedSignature);
+ }
+ }
+ }
+ return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
}
}
}
}
return type;
}
+ function skippedGenericFunction(node, checkMode) {
+ if (checkMode & 2 /* Inferential */) {
+ // We have skipped a generic function during inferential typing. Obtain the inference context and
+ // indicate this has occurred such that we know a second pass of inference is be needed.
+ var context = getInferenceContext(node);
+ context.flags |= 4 /* SkippedGenericFunction */;
+ }
+ }
+ function hasInferenceCandidates(info) {
+ return !!(info.candidates || info.contraCandidates);
+ }
+ function hasOverlappingInferences(a, b) {
+ for (var i = 0; i < a.length; i++) {
+ if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ function mergeInferences(target, source) {
+ for (var i = 0; i < target.length; i++) {
+ if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
+ target[i] = source[i];
+ }
+ }
+ }
+ function getUniqueTypeParameters(context, typeParameters) {
+ var result = [];
+ var oldTypeParameters;
+ var newTypeParameters;
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var tp = typeParameters_2[_i];
+ var name = tp.symbol.escapedName;
+ if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
+ var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
+ var symbol = createSymbol(262144 /* TypeParameter */, newName);
+ var newTypeParameter = createTypeParameter(symbol);
+ newTypeParameter.target = tp;
+ oldTypeParameters = ts.append(oldTypeParameters, tp);
+ newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
+ result.push(newTypeParameter);
+ }
+ else {
+ result.push(tp);
+ }
+ }
+ if (newTypeParameters) {
+ var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
+ for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
+ var tp = newTypeParameters_1[_a];
+ tp.mapper = mapper;
+ }
+ }
+ return result;
+ }
+ function hasTypeParameterByName(typeParameters, name) {
+ return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
+ }
+ function getUniqueTypeParameterName(typeParameters, baseName) {
+ var len = baseName.length;
+ while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
+ len--;
+ var s = baseName.slice(0, len);
+ for (var index = 1; true; index++) {
+ var augmentedName = (s + index);
+ if (!hasTypeParameterByName(typeParameters, augmentedName)) {
+ return augmentedName;
+ }
+ }
+ }
/**
* Returns the type of an expression. Unlike checkExpression, this function is simply concerned
* with computing the type and may not fully check all contained sub-expressions for errors.
@@ -52156,7 +52945,7 @@
return getReturnTypeOfSignature(signature);
}
}
- else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) {
+ else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
return getTypeFromTypeNode(expr.type);
}
// Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions
@@ -52178,27 +52967,22 @@
}
var saveContextualType = node.contextualType;
node.contextualType = anyType;
- var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */);
+ var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
node.contextualType = saveContextualType;
return type;
}
- // 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
- // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function
- // object, it serves as an indicator that all contained function and arrow expressions should be considered to
- // have the wildcard function type; this form of type check is used during overload resolution to exclude
- // contextually typed function and arrow expressions in the initial phase.
function checkExpression(node, checkMode, forceTuple) {
- var type;
- if (node.kind === 148 /* QualifiedName */) {
- type = checkQualifiedName(node);
- }
- else {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
- type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
- }
+ var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
if (isConstEnumObjectType(type)) {
+ checkConstEnumAccess(node, type);
+ }
+ currentNode = saveCurrentNode;
+ return type;
+ }
+ function checkConstEnumAccess(node, type) {
// enum object type for const enums are only permitted in:
// - 'left' in property access
// - 'object' in indexed access
@@ -52210,8 +52994,13 @@
if (!ok) {
error(node, ts.Diagnostics.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);
}
+ if (compilerOptions.isolatedModules) {
+ ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
+ var constEnumDeclaration = type.symbol.valueDeclaration;
+ if (constEnumDeclaration.flags & 4194304 /* Ambient */) {
+ error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
+ }
}
- return type;
}
function checkParenthesizedExpression(node, checkMode) {
var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
@@ -52253,6 +53042,8 @@
return checkObjectLiteral(node, checkMode);
case 189 /* PropertyAccessExpression */:
return checkPropertyAccessExpression(node);
+ case 148 /* QualifiedName */:
+ return checkQualifiedName(node);
case 190 /* ElementAccessExpression */:
return checkIndexedAccess(node);
case 191 /* CallExpression */:
@@ -52261,7 +53052,7 @@
}
/* falls through */
case 192 /* NewExpression */:
- return checkCallExpression(node);
+ return checkCallExpression(node, checkMode);
case 193 /* TaggedTemplateExpression */:
return checkTaggedTemplateExpression(node);
case 195 /* ParenthesizedExpression */:
@@ -52326,9 +53117,8 @@
checkSourceElement(node.constraint);
checkSourceElement(node.default);
var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
- if (!hasNonCircularBaseConstraint(typeParameter)) {
- error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter));
- }
+ // Resolve base constraint to reveal circularity errors
+ getBaseConstraintOfType(typeParameter);
if (!hasNonCircularTypeParameterDefault(typeParameter)) {
error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
}
@@ -52370,7 +53160,7 @@
}
// 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) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) {
+ if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) {
error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
}
}
@@ -52381,7 +53171,8 @@
error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
return;
}
- var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent));
+ var signature = getSignatureFromDeclaration(parent);
+ var typePredicate = getTypePredicateOfSignature(signature);
if (!typePredicate) {
return;
}
@@ -52392,12 +53183,12 @@
}
else {
if (typePredicate.parameterIndex >= 0) {
- if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) {
+ if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) {
error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
}
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]), node.type,
+ checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type,
/*headMessage*/ undefined, leadingError);
}
}
@@ -52464,7 +53255,7 @@
var functionFlags = ts.getFunctionFlags(node);
if (!(functionFlags & 4 /* Invalid */)) {
// Async generators prior to ESNext require the __await and __asyncGenerator helpers
- if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) {
+ if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */);
}
// Async functions prior to ES2017 require the __awaiter helper
@@ -52521,7 +53312,7 @@
checkAsyncFunctionReturnType(node, returnTypeNode);
}
}
- if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) {
+ if (node.kind !== 162 /* IndexSignature */ && node.kind !== 294 /* JSDocFunctionType */) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -53200,7 +53991,7 @@
for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) {
var signature = signatures_6[_a];
if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
- error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation);
+ ts.addRelatedInfo(error(signature.declaration, ts.Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), ts.createDiagnosticForNode(bodyDeclaration, ts.Diagnostics.The_implementation_signature_is_declared_here));
break;
}
}
@@ -53277,8 +54068,8 @@
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
// A jsdoc typedef and callback are, by definition, type aliases
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return 2 /* ExportType */;
case 244 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
@@ -53287,7 +54078,7 @@
case 240 /* ClassDeclaration */:
case 243 /* EnumDeclaration */:
return 2 /* ExportType */ | 1 /* ExportValue */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
case 254 /* ExportAssignment */:
// Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
@@ -53652,8 +54443,8 @@
}
function getEntityNameForDecoratorMetadataFromTypeList(types) {
var commonEntityName;
- for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
- var typeNode = types_16[_i];
+ for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
+ var typeNode = types_17[_i];
while (typeNode.kind === 177 /* ParenthesizedType */) {
typeNode = typeNode.type; // Skip parens if need be
}
@@ -53928,7 +54719,7 @@
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
case 246 /* CaseBlock */:
@@ -54021,8 +54812,8 @@
return;
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];
+ for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
+ var typeParameter = typeParameters_3[_i];
if (!isTypeParameterUnused(typeParameter))
continue;
var name = ts.idText(typeParameter.name);
@@ -54275,7 +55066,7 @@
}
// 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 === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
+ if (parent.kind === 284 /* 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));
}
@@ -54290,7 +55081,7 @@
}
// 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 === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
+ if (parent.kind === 284 /* 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));
}
@@ -54347,7 +55138,7 @@
(container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) ||
container.kind === 245 /* ModuleBlock */ ||
container.kind === 244 /* ModuleDeclaration */ ||
- container.kind === 279 /* SourceFile */);
+ container.kind === 284 /* 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
@@ -54447,7 +55238,7 @@
}
}
if (node.kind === 186 /* BindingElement */) {
- if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) {
+ if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 7 /* ESNext */) {
checkExternalEmitHelpers(node, 4 /* Rest */);
}
// check computed properties inside property names of binding elements
@@ -54458,7 +55249,7 @@
var parent = node.parent.parent;
var parentType = getTypeForBindingElementParent(parent);
var name = node.propertyName || node.name;
- if (!ts.isBindingPattern(name) && parentType) {
+ if (parentType && !ts.isBindingPattern(name)) {
var exprType = getLiteralTypeFromPropertyName(name);
if (isTypeUsableAsPropertyName(exprType)) {
var nameText = getPropertyNameFromType(exprType);
@@ -54645,7 +55436,7 @@
checkGrammarForInOrForOfStatement(node);
if (node.awaitModifier) {
var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
- if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) {
+ if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 7 /* ESNext */) {
// for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */);
}
@@ -55090,7 +55881,7 @@
// If the function has a return type, but promisedType is
// undefined, an error will be reported in checkAsyncFunctionReturnType
// so we don't need to report one here.
- checkTypeAssignableTo(awaitedType, promisedType, node);
+ checkTypeAssignableToAndOptionallyElaborate(awaitedType, promisedType, node, node.expression);
}
}
else {
@@ -55690,8 +56481,8 @@
for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
var base = baseTypes_2[_i];
var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
- for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) {
- var prop = properties_7[_a];
+ for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
+ var prop = properties_6[_a];
var existing = seen.get(prop.escapedName);
if (!existing) {
seen.set(prop.escapedName, { prop: prop, containingType: base });
@@ -55961,10 +56752,6 @@
checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
checkExportsOnMergedDeclarations(node);
computeEnumMemberValues(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);
- }
// Spec 2014 - Section 9.3:
// It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
// and when an enum type has multiple declarations, only one declaration is permitted to omit a value
@@ -55975,9 +56762,10 @@
var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
if (node === firstDeclaration) {
if (enumSymbol.declarations.length > 1) {
+ var enumIsConst_1 = ts.isEnumConst(node);
// check that const is placed\omitted on all enum declarations
ts.forEach(enumSymbol.declarations, function (decl) {
- if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) {
+ if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
}
});
@@ -56058,8 +56846,8 @@
var symbol = getSymbolOfNode(node);
// The following checks only apply on a non-ambient instantiated module declaration.
if (symbol.flags & 512 /* ValueModule */
- && symbol.declarations.length > 1
&& !inAmbientContext
+ && symbol.declarations.length > 1
&& isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
if (firstNonAmbientClassOrFunc) {
@@ -56200,7 +56988,7 @@
return false;
}
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule) {
error(moduleName, node.kind === 255 /* ExportDeclaration */ ?
ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
@@ -56331,7 +57119,7 @@
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ &&
!node.moduleSpecifier && node.flags & 4194304 /* Ambient */;
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
}
}
@@ -56348,7 +57136,7 @@
}
}
function checkGrammarModuleElementContext(node, errorMessage) {
- var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
+ var isInAppropriateContext = node.parent.kind === 284 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
if (!isInAppropriateContext) {
grammarErrorOnFirstToken(node, errorMessage);
}
@@ -56377,7 +57165,7 @@
// If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
return;
}
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
if (node.isExportEquals) {
error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
@@ -56470,9 +57258,14 @@
!!declaration.body;
}
function checkSourceElement(node) {
- if (!node) {
- return;
+ if (node) {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
+ checkSourceElementWorker(node);
+ currentNode = saveCurrentNode;
+ }
}
+ function checkSourceElementWorker(node) {
if (ts.isInJSFile(node)) {
ts.forEach(node.jsDoc, function (_a) {
var tags = _a.tags;
@@ -56542,32 +57335,32 @@
return checkInferType(node);
case 183 /* ImportType */:
return checkImportType(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return checkJSDocAugmentsTag(node);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return checkJSDocTypeAliasTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return checkJSDocTemplateTag(node);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return checkJSDocTypeTag(node);
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
return checkJSDocParameterTag(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
checkJSDocFunctionType(node);
// falls through
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
- case 292 /* JSDocTypeLiteral */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
+ case 297 /* JSDocTypeLiteral */:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
checkJSDocVariadicType(node);
return;
- case 283 /* JSDocTypeExpression */:
+ case 288 /* JSDocTypeExpression */:
return checkSourceElement(node.type);
case 180 /* IndexedAccessType */:
return checkIndexedAccessType(node);
@@ -56721,10 +57514,13 @@
}
function checkDeferredNodes(context) {
var links = getNodeLinks(context);
- if (!links.deferredNodes) {
- return;
+ if (links.deferredNodes) {
+ links.deferredNodes.forEach(checkDeferredNode);
}
- links.deferredNodes.forEach(function (node) {
+ }
+ function checkDeferredNode(node) {
+ var saveCurrentNode = currentNode;
+ currentNode = node;
switch (node.kind) {
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
@@ -56746,7 +57542,7 @@
checkJsxElementDeferred(node);
break;
}
- });
+ currentNode = saveCurrentNode;
}
function checkSourceFile(node) {
ts.performance.mark("beforeCheck");
@@ -56821,7 +57617,7 @@
throwIfNonDiagnosticsProducing();
if (sourceFile) {
// Some global diagnostics are deferred until they are needed and
- // may not be reported in the firt call to getGlobalDiagnostics.
+ // may not be reported in the first call to getGlobalDiagnostics.
// We should catch these changes and report them.
var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
@@ -56872,7 +57668,7 @@
copySymbols(location.locals, meaning);
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
// falls through
@@ -57091,10 +57887,10 @@
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 299 /* JSDocParameterTag */) {
+ if (entityName.parent.kind === 304 /* JSDocParameterTag */) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) {
+ if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 308 /* JSDocTemplateTag */) {
ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true.
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -57136,7 +57932,7 @@
return undefined;
}
function getSymbolAtLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
}
var parent = node.parent;
@@ -57478,7 +58274,7 @@
}
var parentSymbol_1 = getParentOfSymbol(symbol);
if (parentSymbol_1) {
- if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) {
+ if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 284 /* 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.
@@ -57505,7 +58301,7 @@
return undefined;
}
function isSymbolOfDeclarationWithCollidingName(symbol) {
- if (symbol.flags & 418 /* BlockScoped */) {
+ if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
var links = getSymbolLinks(symbol);
if (links.isDeclarationWithCollidingName === undefined) {
var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
@@ -57593,7 +58389,7 @@
}
function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
- if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
+ if (node === undefined || node.parent.kind !== 284 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
// parent is not source file or it is not reference to internal module
return false;
}
@@ -58022,7 +58818,7 @@
break;
}
}
- if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
+ if (current.valueDeclaration && current.valueDeclaration.kind === 284 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
return false;
}
// check that at least one declaration of top level symbol originates from type declaration file
@@ -58055,7 +58851,7 @@
if (!moduleSymbol) {
return undefined;
}
- return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */);
+ return ts.getDeclarationOfKind(moduleSymbol, 284 /* SourceFile */);
}
function initializeTypeChecker() {
// Bind all source files and propagate errors
@@ -58133,7 +58929,7 @@
// autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
}
- globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1);
+ globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
if (augmentations) {
@@ -58169,8 +58965,8 @@
else {
// Otherwise issue top-level error since the files appear very identical in terms of what they contain
var list = ts.arrayFrom(conflictingSymbols.keys()).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)));
+ diagnostics.add(ts.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(ts.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;
@@ -58287,7 +59083,7 @@
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
}
else if (flags & 128 /* Abstract */) {
@@ -58310,7 +59106,7 @@
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
}
else if (node.kind === 151 /* Parameter */) {
@@ -58355,7 +59151,7 @@
flags |= 1 /* Export */;
break;
case 80 /* DefaultKeyword */:
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
}
@@ -58478,7 +59274,7 @@
case 151 /* Parameter */:
return false;
default:
- if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return false;
}
switch (node.kind) {
@@ -58566,10 +59362,10 @@
var nonSimpleParameters = getNonSimpleParameters(node.parameters);
if (ts.length(nonSimpleParameters)) {
ts.forEach(nonSimpleParameters, function (parameter) {
- addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
+ ts.addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here));
});
var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); });
- addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
+ ts.addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1));
return true;
}
}
@@ -59006,6 +59802,11 @@
return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
}
}
+ else if (node.operator === 133 /* ReadonlyKeyword */) {
+ if (node.type.kind !== 169 /* ArrayType */ && node.type.kind !== 170 /* TupleType */) {
+ return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(139 /* SymbolKeyword */));
+ }
+ }
}
function checkGrammarForInvalidDynamicName(node, message) {
if (isNonBindableDynamicName(node)) {
@@ -59396,7 +60197,7 @@
// 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 === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
var links_2 = getNodeLinks(node.parent);
// Check if the containing block ever report this error
if (!links_2.hasReportedStatementInAmbientContext) {
@@ -59436,7 +60237,7 @@
var literalType = ts.isLiteralTypeNode(node.parent) ||
ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
if (!literalType) {
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) {
return true;
}
@@ -59601,10 +60402,11 @@
return createLiteralFromNode(value);
}
ts.createLiteral = createLiteral;
- function createNumericLiteral(value) {
+ function createNumericLiteral(value, numericLiteralFlags) {
+ if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
var node = createSynthesizedNode(8 /* NumericLiteral */);
node.text = value;
- node.numericLiteralFlags = 0;
+ node.numericLiteralFlags = numericLiteralFlags;
return node;
}
ts.createNumericLiteral = createNumericLiteral;
@@ -61449,14 +62251,14 @@
// JSDoc
/* @internal */
function createJSDocTypeExpression(type) {
- var node = createSynthesizedNode(283 /* JSDocTypeExpression */);
+ var node = createSynthesizedNode(288 /* JSDocTypeExpression */);
node.type = type;
return node;
}
ts.createJSDocTypeExpression = createJSDocTypeExpression;
/* @internal */
function createJSDocTypeTag(typeExpression, comment) {
- var tag = createJSDocTag(302 /* JSDocTypeTag */, "type");
+ var tag = createJSDocTag(307 /* JSDocTypeTag */, "type");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61464,7 +62266,7 @@
ts.createJSDocTypeTag = createJSDocTypeTag;
/* @internal */
function createJSDocReturnTag(typeExpression, comment) {
- var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns");
+ var tag = createJSDocTag(305 /* JSDocReturnTag */, "returns");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61472,7 +62274,7 @@
ts.createJSDocReturnTag = createJSDocReturnTag;
/* @internal */
function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
- var tag = createJSDocTag(299 /* JSDocParameterTag */, "param");
+ var tag = createJSDocTag(304 /* JSDocParameterTag */, "param");
tag.typeExpression = typeExpression;
tag.name = name;
tag.isBracketed = isBracketed;
@@ -61482,7 +62284,7 @@
ts.createJSDocParamTag = createJSDocParamTag;
/* @internal */
function createJSDocComment(comment, tags) {
- var node = createSynthesizedNode(291 /* JSDocComment */);
+ var node = createSynthesizedNode(296 /* JSDocComment */);
node.comment = comment;
node.tags = tags;
return node;
@@ -61563,6 +62365,28 @@
return node;
}
ts.createJsxFragment = createJsxFragment;
+ function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
+ var node = createSynthesizedNode(11 /* JsxText */);
+ node.text = text;
+ node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
+ return node;
+ }
+ ts.createJsxText = createJsxText;
+ function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
+ return node.text !== text
+ || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
+ ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
+ : node;
+ }
+ ts.updateJsxText = updateJsxText;
+ function createJsxOpeningFragment() {
+ return createSynthesizedNode(265 /* JsxOpeningFragment */);
+ }
+ ts.createJsxOpeningFragment = createJsxOpeningFragment;
+ function createJsxJsxClosingFragment() {
+ return createSynthesizedNode(266 /* JsxClosingFragment */);
+ }
+ ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment;
function updateJsxFragment(node, openingFragment, children, closingFragment) {
return node.openingFragment !== openingFragment
|| node.children !== children
@@ -61741,7 +62565,7 @@
(typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
(libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
(hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
- var updated = createSynthesizedNode(279 /* SourceFile */);
+ var updated = createSynthesizedNode(284 /* SourceFile */);
updated.flags |= node.flags;
updated.statements = createNodeArray(statements);
updated.endOfFileToken = node.endOfFileToken;
@@ -61825,7 +62649,7 @@
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(307 /* NotEmittedStatement */);
+ var node = createSynthesizedNode(312 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
@@ -61837,7 +62661,7 @@
*/
/* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(316 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -61849,7 +62673,7 @@
*/
/* @internal */
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(310 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(315 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -61864,7 +62688,7 @@
* @param location The location for the expression. Defaults to the positions from "original" if provided.
*/
function createPartiallyEmittedExpression(expression, original) {
- var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */);
+ var node = createSynthesizedNode(313 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -61880,7 +62704,7 @@
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
function flattenCommaElements(node) {
if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
- if (node.kind === 309 /* CommaListExpression */) {
+ if (node.kind === 314 /* CommaListExpression */) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
@@ -61890,7 +62714,7 @@
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(309 /* CommaListExpression */);
+ var node = createSynthesizedNode(314 /* CommaListExpression */);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -61903,33 +62727,197 @@
ts.updateCommaList = updateCommaList;
function createBundle(sourceFiles, prepends) {
if (prepends === void 0) { prepends = ts.emptyArray; }
- var node = ts.createNode(280 /* Bundle */);
+ var node = ts.createNode(285 /* Bundle */);
node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, map) {
- var node = ts.createNode(281 /* UnparsedSource */);
+ var allUnscopedEmitHelpers;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
+ ts.valuesHelper,
+ ts.readHelper,
+ ts.spreadHelper,
+ ts.restHelper,
+ ts.decorateHelper,
+ ts.metadataHelper,
+ ts.paramHelper,
+ ts.awaiterHelper,
+ ts.assignHelper,
+ ts.awaitHelper,
+ ts.asyncGeneratorHelper,
+ ts.asyncDelegator,
+ ts.asyncValues,
+ ts.extendsHelper,
+ ts.templateObjectHelper,
+ ts.generatorHelper,
+ ts.importStarHelper,
+ ts.importDefaultHelper
+ ], function (helper) { return helper.name; }));
+ }
+ function createUnparsedSource() {
+ var node = ts.createNode(286 /* UnparsedSource */);
+ node.prologues = ts.emptyArray;
+ node.referencedFiles = ts.emptyArray;
+ node.libReferenceDirectives = ts.emptyArray;
+ node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
+ return node;
+ }
+ function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
+ var node = createUnparsedSource();
+ var stripInternal;
+ var bundleFileInfo;
if (!ts.isString(textOrInputFiles)) {
ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
- node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath;
+ node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
Object.defineProperties(node, {
text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
});
+ if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
+ node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
+ ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
+ stripInternal = mapTextOrStripInternal;
+ bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
+ if (node.oldFileOfCurrentEmit) {
+ parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo));
+ return node;
+ }
+ }
}
else {
+ node.fileName = "";
node.text = textOrInputFiles;
node.sourceMapPath = mapPathOrType;
- node.sourceMapText = map;
+ node.sourceMapText = mapTextOrStripInternal;
}
+ ts.Debug.assert(!node.oldFileOfCurrentEmit);
+ parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
return node;
}
ts.createUnparsedSourceFile = createUnparsedSourceFile;
- function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapText) {
- var node = ts.createNode(282 /* InputFiles */);
+ function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
+ var prologues;
+ var helpers;
+ var referencedFiles;
+ var typeReferenceDirectives;
+ var libReferenceDirectives;
+ var texts;
+ for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "prologue" /* Prologue */:
+ (prologues || (prologues = [])).push(createUnparsedNode(section, node));
+ break;
+ case "emitHelpers" /* EmitHelpers */:
+ (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ node.hasNoDefaultLib = true;
+ break;
+ case "reference" /* Reference */:
+ (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "type" /* Type */:
+ (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
+ break;
+ case "lib" /* Lib */:
+ (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "prepend" /* Prepend */:
+ var prependNode = createUnparsedNode(section, node);
+ var prependTexts = void 0;
+ for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
+ var text = _c[_b];
+ if (!stripInternal || text.kind !== "internal" /* Internal */) {
+ (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
+ }
+ }
+ prependNode.texts = prependTexts || ts.emptyArray;
+ (texts || (texts = [])).push(prependNode);
+ break;
+ case "internal" /* Internal */:
+ if (stripInternal)
+ break;
+ // falls through
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.prologues = prologues || ts.emptyArray;
+ node.helpers = helpers;
+ node.referencedFiles = referencedFiles || ts.emptyArray;
+ node.typeReferenceDirectives = typeReferenceDirectives;
+ node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
+ node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
+ }
+ function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
+ ts.Debug.assert(!!node.oldFileOfCurrentEmit);
+ var texts;
+ var syntheticReferences;
+ for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "internal" /* Internal */:
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
+ break;
+ // Ignore
+ case "prologue" /* Prologue */:
+ case "emitHelpers" /* EmitHelpers */:
+ case "prepend" /* Prepend */:
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.texts = texts || ts.emptyArray;
+ node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
+ node.syntheticReferences = syntheticReferences;
+ return node;
+ }
+ function mapBundleFileSectionKindToSyntaxKind(kind) {
+ switch (kind) {
+ case "prologue" /* Prologue */: return 279 /* UnparsedPrologue */;
+ case "prepend" /* Prepend */: return 280 /* UnparsedPrepend */;
+ case "internal" /* Internal */: return 282 /* UnparsedInternalText */;
+ case "text" /* Text */: return 281 /* UnparsedText */;
+ case "emitHelpers" /* EmitHelpers */:
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
+ default:
+ return ts.Debug.assertNever(kind);
+ }
+ }
+ function createUnparsedNode(section, parent) {
+ var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ return node;
+ }
+ function createUnparsedSyntheticReference(section, parent) {
+ var node = ts.createNode(283 /* UnparsedSyntheticReference */, section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ node.section = section;
+ return node;
+ }
+ function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
+ var node = ts.createNode(287 /* InputFiles */);
if (!ts.isString(javascriptTextOrReadFileText)) {
var cache_1 = ts.createMap();
var textGetter_1 = function (path) {
@@ -61946,15 +62934,25 @@
var result = textGetter_1(path);
return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
};
+ var buildInfo_1;
+ var getAndCacheBuildInfo_1 = function (getText) {
+ if (buildInfo_1 === undefined) {
+ var result = getText();
+ buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
+ }
+ return buildInfo_1 || undefined;
+ };
node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath;
node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath;
+ node.buildInfoPath = declarationMapTextOrBuildInfoPath;
Object.defineProperties(node, {
javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
- declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } } // TODO:: if there is inline sourceMap in dtsFile, use that
+ declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
+ buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
});
}
else {
@@ -61963,7 +62961,12 @@
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
node.declarationText = declarationTextOrJavascriptPath;
node.declarationMapPath = declarationMapPath;
- node.declarationMapText = declarationMapText;
+ node.declarationMapText = declarationMapTextOrBuildInfoPath;
+ node.javascriptPath = javascriptPath;
+ node.declarationPath = declarationPath,
+ node.buildInfoPath = buildInfoPath;
+ node.buildInfo = buildInfo;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
}
return node;
}
@@ -62101,10 +63104,10 @@
// 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 === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return node.emitNode = { annotatedNodes: [node] };
}
- var sourceFile = ts.getSourceFileOfNode(node);
+ var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
}
node.emitNode = {};
@@ -62402,7 +63405,7 @@
ts.nullTransformationContext = {
enableEmitNotification: ts.noop,
enableSubstitution: ts.noop,
- endLexicalEnvironment: function () { return undefined; },
+ endLexicalEnvironment: ts.returnUndefined,
getCompilerOptions: ts.notImplemented,
getEmitHost: ts.notImplemented,
getEmitResolver: ts.notImplemented,
@@ -62547,38 +63550,38 @@
return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
}
ts.getHelperName = getHelperName;
- var valuesHelper = {
+ ts.valuesHelper = {
name: "typescript:values",
scoped: false,
text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };"
};
function createValuesHelper(context, expression, location) {
- context.requestEmitHelper(valuesHelper);
+ context.requestEmitHelper(ts.valuesHelper);
return ts.setTextRange(ts.createCall(getHelperName("__values"),
/*typeArguments*/ undefined, [expression]), location);
}
ts.createValuesHelper = createValuesHelper;
- var readHelper = {
+ ts.readHelper = {
name: "typescript:read",
scoped: false,
text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };"
};
function createReadHelper(context, iteratorRecord, count, location) {
- context.requestEmitHelper(readHelper);
+ context.requestEmitHelper(ts.readHelper);
return ts.setTextRange(ts.createCall(getHelperName("__read"),
/*typeArguments*/ undefined, count !== undefined
? [iteratorRecord, ts.createLiteral(count)]
: [iteratorRecord]), location);
}
ts.createReadHelper = createReadHelper;
- var spreadHelper = {
+ ts.spreadHelper = {
name: "typescript:spread",
scoped: false,
text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
};
function createSpreadHelper(context, argumentList, location) {
- context.requestEmitHelper(readHelper);
- context.requestEmitHelper(spreadHelper);
+ context.requestEmitHelper(ts.readHelper);
+ context.requestEmitHelper(ts.spreadHelper);
return ts.setTextRange(ts.createCall(getHelperName("__spread"),
/*typeArguments*/ undefined, argumentList), location);
}
@@ -62749,7 +63752,7 @@
function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) {
var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
if (property === firstAccessor) {
- var properties_8 = [];
+ var properties_7 = [];
if (getAccessor) {
var getterFunction = ts.createFunctionExpression(getAccessor.modifiers,
/*asteriskToken*/ undefined,
@@ -62760,7 +63763,7 @@
ts.setTextRange(getterFunction, getAccessor);
ts.setOriginalNode(getterFunction, getAccessor);
var getter = ts.createPropertyAssignment("get", getterFunction);
- properties_8.push(getter);
+ properties_7.push(getter);
}
if (setAccessor) {
var setterFunction = ts.createFunctionExpression(setAccessor.modifiers,
@@ -62772,15 +63775,15 @@
ts.setTextRange(setterFunction, setAccessor);
ts.setOriginalNode(setterFunction, setAccessor);
var setter = ts.createPropertyAssignment("set", setterFunction);
- properties_8.push(setter);
+ properties_7.push(setter);
}
- properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
- properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
+ properties_7.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
+ properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"),
/*typeArguments*/ undefined, [
receiver,
createExpressionForPropertyName(property.name),
- ts.createObjectLiteral(properties_8, multiLine)
+ ts.createObjectLiteral(properties_7, multiLine)
]),
/*location*/ firstAccessor);
return ts.aggregateTransformFlags(expression);
@@ -63424,7 +64427,7 @@
case 190 /* ElementAccessExpression */:
case 189 /* PropertyAccessExpression */:
case 213 /* NonNullExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -63440,7 +64443,7 @@
ts.parenthesizeConciseBody = parenthesizeConciseBody;
function isCommaSequence(node) {
return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
- node.kind === 309 /* CommaListExpression */;
+ node.kind === 314 /* CommaListExpression */;
}
ts.isCommaSequence = isCommaSequence;
var OuterExpressionKinds;
@@ -63459,7 +64462,7 @@
case 212 /* AsExpression */:
case 213 /* NonNullExpression */:
return (kinds & 2 /* Assertions */) !== 0;
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
}
return false;
@@ -63496,7 +64499,7 @@
case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
- case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 313 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
/**
@@ -64288,12 +65291,12 @@
case 278 /* EnumMember */:
return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
// No need to visit nodes with no children.
@@ -64349,7 +65352,7 @@
case 220 /* EmptyStatement */:
case 210 /* OmittedExpression */:
case 236 /* DebuggerStatement */:
- case 307 /* NotEmittedStatement */:
+ case 312 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
@@ -64726,14 +65729,14 @@
result = reduceNode(node.initializer, cbNode, result);
break;
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
result = reduceNodes(node.statements, cbNodes, result);
break;
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -64747,8 +65750,8 @@
return statements;
}
return ts.isNodeArray(statements)
- ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements)
- : ts.addStatementsAfterPrologue(statements, declarations);
+ ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements)
+ : ts.insertStatementsAfterStandardPrologue(statements, declarations);
}
ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
/**
@@ -65014,7 +66017,7 @@
}
exit();
}
- function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) {
+ function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
var _a;
ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
@@ -65024,6 +66027,14 @@
var nameIndexToNewNameIndexMap;
var mappingIterator = decodeMappings(map.mappings);
for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) {
+ if (end && (raw.generatedLine > end.line ||
+ (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
+ break;
+ }
+ if (start && (raw.generatedLine < start.line ||
+ (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
+ continue;
+ }
// Then reencode all the updated mappings into the overall map
var newSourceIndex = void 0;
var newSourceLine = void 0;
@@ -65052,8 +66063,10 @@
}
}
}
- var newGeneratedLine = raw.generatedLine + generatedLine;
- var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter;
+ var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
+ var newGeneratedLine = rawGeneratedLine + generatedLine;
+ var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
+ var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
}
exit();
@@ -65536,7 +66549,7 @@
function chainBundle(transformSourceFile) {
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
+ return node.kind === 284 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
}
function transformBundle(node) {
return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
@@ -66012,8 +67025,8 @@
if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
if (flattenContext.level >= 1 /* ObjectRest */
- && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */))
- && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */))
+ && !(element.transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */))
+ && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */))
&& !ts.isComputedPropertyName(propertyName)) {
bindingElements = ts.append(bindingElements, element);
}
@@ -66079,7 +67092,7 @@
if (flattenContext.level >= 1 /* ObjectRest */) {
// If an array pattern contains an ObjectRest, we must cache the result so that we
// can perform the ObjectRest destructuring in a different declaration
- if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (element.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
if (flattenContext.hoistTempVariables) {
flattenContext.context.hoistVariableDeclaration(temp);
@@ -66197,7 +67210,7 @@
function makeAssignmentElement(name) {
return name;
}
- var restHelper = {
+ ts.restHelper = {
name: "typescript:rest",
scoped: false,
text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
@@ -66206,7 +67219,7 @@
* `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
*/
function createRestCall(context, value, elements, computedTempVariables, location) {
- context.requestEmitHelper(restHelper);
+ context.requestEmitHelper(ts.restHelper);
var propertyNames = [];
var computedTempVariableOffset = 0;
for (var i = 0; i < elements.length - 1; i++) {
@@ -66307,14 +67320,14 @@
var pendingExpressions;
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* 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 === 282 /* InputFiles */) {
+ if (prepend.kind === 287 /* InputFiles */) {
return ts.createUnparsedSourceFile(prepend, "js");
}
return prepend;
@@ -66363,7 +67376,7 @@
*/
function onBeforeVisitNode(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 245 /* ModuleBlock */:
case 218 /* Block */:
@@ -66407,14 +67420,9 @@
* @param node The node to visit.
*/
function visitorWorker(node) {
- if (node.transformFlags & 1 /* TypeScript */) {
- // This node is explicitly marked as TypeScript, so we should transform the node.
+ if (node.transformFlags & 1 /* ContainsTypeScript */) {
return visitTypeScript(node);
}
- else if (node.transformFlags & 2 /* ContainsTypeScript */) {
- // This node contains TypeScript, so we should visit its children.
- return ts.visitEachChild(node, visitor, context);
- }
return node;
}
/**
@@ -66448,7 +67456,7 @@
// As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
// We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
// and will trigger debug failures when debug verbosity is turned up
- if (node.transformFlags & 2 /* ContainsTypeScript */) {
+ if (node.transformFlags & 1 /* ContainsTypeScript */) {
// This node contains TypeScript, so we should visit its children.
return ts.visitEachChild(node, visitor, context);
}
@@ -66490,15 +67498,9 @@
// do not emit ES6 imports and exports since they are illegal inside a namespace
return undefined;
}
- else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
- // This node is explicitly marked as TypeScript, or is exported at the namespace
- // level, so we should transform the node.
+ else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
return visitTypeScript(node);
}
- else if (node.transformFlags & 2 /* ContainsTypeScript */) {
- // This node contains TypeScript, so we should visit its children.
- return ts.visitEachChild(node, visitor, context);
- }
return node;
}
/**
@@ -66549,7 +67551,7 @@
* @param node The node to visit.
*/
function visitTypeScript(node) {
- if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) {
+ if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) {
// TypeScript ambient declarations are elided, but some comments may be preserved.
// See the implementation of `getLeadingComments` in comments.ts for more details.
return ts.createNotEmittedStatement(node);
@@ -66616,7 +67618,7 @@
// See the implementation of `getLeadingComments` in comments.ts for more details.
return ts.createNotEmittedStatement(node);
case 240 /* ClassDeclaration */:
- // This is a class declaration with TypeScript syntax extensions.
+ // This may be a class declaration with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
// - decorators
@@ -66627,7 +67629,7 @@
// - method overload signatures
return visitClassDeclaration(node);
case 209 /* ClassExpression */:
- // This is a class expression with TypeScript syntax extensions.
+ // This may be a class expression with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
// - decorators
@@ -66638,7 +67640,7 @@
// - method overload signatures
return visitClassExpression(node);
case 273 /* HeritageClause */:
- // This is a heritage clause with TypeScript syntax extensions.
+ // This may be a heritage clause with TypeScript syntax extensions.
//
// TypeScript heritage clause extensions include:
// - `implements` clause
@@ -66666,7 +67668,7 @@
// TypeScript arrow functions can have modifiers and type annotations.
return visitArrowFunction(node);
case 151 /* Parameter */:
- // This is a parameter declaration with TypeScript syntax extensions.
+ // This may be a parameter declaration with TypeScript syntax extensions.
//
// TypeScript parameter declaration syntax extensions include:
// - decorators
@@ -66707,7 +67709,8 @@
// TypeScript namespace or external module import.
return visitImportEqualsDeclaration(node);
default:
- return ts.Debug.failBadSyntaxKind(node);
+ // node contains some other TypeScript syntax
+ return ts.visitEachChild(node, visitor, context);
}
}
function visitSourceFile(node) {
@@ -66756,18 +67759,19 @@
facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
return facts;
}
- /**
- * Transforms a class declaration with TypeScript syntax into compatible ES6.
- *
- * This function will only be called when one of the following conditions are met:
- * - The class has decorators.
- * - The class has property declarations with initializers.
- * - The class contains a constructor that contains parameters with accessibility modifiers.
- * - The class is an export in a TypeScript namespace.
- *
- * @param node The node to transform.
- */
+ function hasTypeScriptClassSyntax(node) {
+ return !!(node.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */);
+ }
+ function isClassLikeDeclarationWithTypeScriptSyntax(node) {
+ return ts.some(node.decorators)
+ || ts.some(node.typeParameters)
+ || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
+ || ts.some(node.members, hasTypeScriptClassSyntax);
+ }
function visitClassDeclaration(node) {
+ if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) {
+ return ts.visitEachChild(node, visitor, context);
+ }
var savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
@@ -66820,7 +67824,7 @@
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
var iife = ts.createImmediatelyInvokedArrowFunction(statements);
ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
var varStatement = ts.createVariableStatement(
@@ -66997,16 +68001,10 @@
ts.setCommentRange(statement, node);
return statement;
}
- /**
- * Transforms a class expression with TypeScript syntax into compatible ES6.
- *
- * This function will only be called when one of the following conditions are met:
- * - The class has property declarations with initializers.
- * - The class contains a constructor that contains parameters with accessibility modifiers.
- *
- * @param node The node to transform.
- */
function visitClassExpression(node) {
+ if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
+ return ts.visitEachChild(node, visitor, context);
+ }
var savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
@@ -67070,7 +68068,7 @@
var constructor = ts.getFirstConstructorWithBody(node);
var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty);
var hasParameterPropertyAssignments = constructor &&
- constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ &&
+ constructor.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */ &&
ts.forEach(constructor.parameters, isParameterWithPropertyAssignment);
// If the class does not contain nodes that require a synthesized constructor,
// accept the current constructor if it exists.
@@ -67269,8 +68267,8 @@
* @param receiver The receiver on which each property should be assigned.
*/
function addInitializedPropertyStatements(statements, properties, receiver) {
- for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
- var property = properties_9[_i];
+ for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
+ var property = properties_8[_i];
var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver));
ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
ts.setCommentRange(statement, property);
@@ -67286,8 +68284,8 @@
*/
function generateInitializedPropertyExpressions(properties, receiver) {
var expressions = [];
- for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) {
- var property = properties_10[_i];
+ for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
+ var property = properties_9[_i];
var expression = transformInitializedProperty(property, receiver);
ts.startOnNewLine(expression);
ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
@@ -67361,11 +68359,14 @@
var decorators;
if (node) {
var parameters = node.parameters;
- for (var i = 0; i < parameters.length; i++) {
- var parameter = parameters[i];
+ var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
+ var firstParameterOffset = firstParameterIsThis ? 1 : 0;
+ var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
+ for (var i = 0; i < numParameters; i++) {
+ var parameter = parameters[i + firstParameterOffset];
if (decorators || parameter.decorators) {
if (!decorators) {
- decorators = new Array(parameters.length);
+ decorators = new Array(numParameters);
}
decorators[i] = parameter.decorators;
}
@@ -67865,8 +68866,12 @@
return serializeTypeList(node.types);
case 175 /* ConditionalType */:
return serializeTypeList([node.trueType, node.falseType]);
- case 167 /* TypeQuery */:
case 179 /* TypeOperator */:
+ if (node.operator === 133 /* ReadonlyKeyword */) {
+ return serializeTypeNode(node.type);
+ }
+ break;
+ case 167 /* TypeQuery */:
case 180 /* IndexedAccessType */:
case 181 /* MappedType */:
case 168 /* TypeLiteral */:
@@ -67884,8 +68889,8 @@
// Note when updating logic here also update getEntityNameForDecoratorMetadata
// so that aliases can be marked as referenced
var serializedUnion;
- for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
- var typeNode = types_17[_i];
+ for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
+ var typeNode = types_18[_i];
while (typeNode.kind === 177 /* ParenthesizedType */) {
typeNode = typeNode.type; // Skip parens if need be
}
@@ -68027,7 +69032,7 @@
* available.
*/
function getGlobalBigIntNameWithFallback() {
- return languageVersion < 6 /* ESNext */
+ return languageVersion < 7 /* ESNext */
? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object"))
: ts.createIdentifier("BigInt");
}
@@ -68111,12 +69116,12 @@
* @param node The HeritageClause to transform.
*/
function visitHeritageClause(node) {
- if (node.token === 86 /* ExtendsKeyword */) {
- var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1);
- return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node);
- }
+ if (node.token === 109 /* ImplementsKeyword */) {
+ // implements clauses are elided
return undefined;
}
+ return ts.visitEachChild(node, visitor, context);
+ }
/**
* Transforms an ExpressionWithTypeArguments with TypeScript syntax.
*
@@ -68151,16 +69156,6 @@
}
return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context));
}
- /**
- * Visits a method declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is an overload
- * - The node is marked as abstract, public, private, protected, or readonly
- * - The node has a computed property name
- *
- * @param node The method node.
- */
function visitMethodDeclaration(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return undefined;
@@ -68187,15 +69182,6 @@
function shouldEmitAccessorDeclaration(node) {
return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));
}
- /**
- * Visits a get accessor declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked as abstract, public, private, or protected
- * - The node has a computed property name
- *
- * @param node The get accessor node.
- */
function visitGetAccessor(node) {
if (!shouldEmitAccessorDeclaration(node)) {
return undefined;
@@ -68211,15 +69197,6 @@
}
return updated;
}
- /**
- * Visits a set accessor declaration of a class.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked as abstract, public, private, or protected
- * - The node has a computed property name
- *
- * @param node The set accessor node.
- */
function visitSetAccessor(node) {
if (!shouldEmitAccessorDeclaration(node)) {
return undefined;
@@ -68234,16 +69211,6 @@
}
return updated;
}
- /**
- * Visits a function declaration.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is an overload
- * - The node is exported from a TypeScript namespace
- * - The node has decorators
- *
- * @param node The function node.
- */
function visitFunctionDeclaration(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return ts.createNotEmittedStatement(node);
@@ -68259,14 +69226,6 @@
}
return updated;
}
- /**
- * Visits a function expression node.
- *
- * This function will be called when one of the following conditions are met:
- * - The node has type annotations
- *
- * @param node The function expression node.
- */
function visitFunctionExpression(node) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return ts.createOmittedExpression();
@@ -68276,51 +69235,31 @@
/*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
return updated;
}
- /**
- * @remarks
- * This function will be called when one of the following conditions are met:
- * - The node has type annotations
- */
function visitArrowFunction(node) {
var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier),
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
/*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
return updated;
}
- /**
- * Visits a parameter declaration node.
- *
- * This function will be called when one of the following conditions are met:
- * - The node has an accessibility modifier.
- * - The node has a questionToken.
- * - The node's kind is ThisKeyword.
- *
- * @param node The parameter declaration node.
- */
function visitParameter(node) {
if (ts.parameterIsThisKeyword(node)) {
return undefined;
}
- var parameter = ts.createParameter(
+ var updated = ts.updateParameter(node,
/*decorators*/ undefined,
/*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName),
/*questionToken*/ undefined,
/*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
+ if (updated !== node) {
// While we emit the source map for the node after skipping decorators and modifiers,
// we need to emit the comments for the original range.
- ts.setOriginalNode(parameter, node);
- ts.setTextRange(parameter, ts.moveRangePastModifiers(node));
- ts.setCommentRange(parameter, node);
- ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node));
- ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */);
- return parameter;
+ ts.setCommentRange(updated, node);
+ ts.setTextRange(updated, ts.moveRangePastModifiers(node));
+ ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
+ ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
+ }
+ return updated;
}
- /**
- * Visits a variable statement in a namespace.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is exported from a TypeScript namespace.
- */
function visitVariableStatement(node) {
if (isExportOfNamespace(node)) {
var variables = ts.getInitializedVariables(node.declarationList);
@@ -68349,12 +69288,6 @@
return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName),
/*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
}
- /**
- * Visits a parenthesized expression that contains either a type assertion or an `as`
- * expression.
- *
- * @param node The parenthesized expression node.
- */
function visitParenthesizedExpression(node) {
var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */);
if (ts.isAssertionExpression(innerExpression)) {
@@ -68491,7 +69424,7 @@
var statements = [];
startLexicalEnvironment();
var members = ts.map(node.members, transformEnumMember);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
ts.addRange(statements, members);
currentNamespaceContainerName = savedCurrentNamespaceLocalName;
return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members),
@@ -68590,7 +69523,7 @@
// 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))
- ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
+ ], currentLexicalScope.kind === 284 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
ts.setOriginalNode(statement, node);
recordEmittedDeclarationInScope(node);
if (isFirstEmittedDeclarationInScope(node)) {
@@ -68738,7 +69671,7 @@
var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
currentNamespaceContainerName = savedCurrentNamespaceContainerName;
currentNamespace = savedCurrentNamespace;
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
@@ -69155,7 +70088,7 @@
// 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 !== 279 /* SourceFile */) {
+ if (container && container.kind !== 284 /* SourceFile */) {
var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) ||
(applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */);
if (substitute) {
@@ -69206,39 +70139,39 @@
argumentsArray.push(descriptor);
}
}
- context.requestEmitHelper(decorateHelper);
+ context.requestEmitHelper(ts.decorateHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"),
/*typeArguments*/ undefined, argumentsArray), location);
}
- var decorateHelper = {
+ ts.decorateHelper = {
name: "typescript:decorate",
scoped: false,
priority: 2,
text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
};
function createMetadataHelper(context, metadataKey, metadataValue) {
- context.requestEmitHelper(metadataHelper);
+ context.requestEmitHelper(ts.metadataHelper);
return ts.createCall(ts.getHelperName("__metadata"),
/*typeArguments*/ undefined, [
ts.createLiteral(metadataKey),
metadataValue
]);
}
- var metadataHelper = {
+ ts.metadataHelper = {
name: "typescript:metadata",
scoped: false,
priority: 3,
text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
};
function createParamHelper(context, expression, parameterOffset, location) {
- context.requestEmitHelper(paramHelper);
+ context.requestEmitHelper(ts.paramHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__param"),
/*typeArguments*/ undefined, [
ts.createLiteral(parameterOffset),
expression
]), location);
}
- var paramHelper = {
+ ts.paramHelper = {
name: "typescript:param",
scoped: false,
priority: 4,
@@ -69293,7 +70226,7 @@
return visited;
}
function visitor(node) {
- if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) {
+ if ((node.transformFlags & 32 /* ContainsES2017 */) === 0) {
return node;
}
switch (node.kind) {
@@ -69563,22 +70496,26 @@
}
var savedCapturedSuperProperties = capturedSuperProperties;
var savedHasSuperElementAccess = hasSuperElementAccess;
+ if (!isArrowFunction) {
capturedSuperProperties = ts.createUnderscoreEscapedMap();
hasSuperElementAccess = false;
+ }
var result;
if (!isArrowFunction) {
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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
if (emitSuperHelpers) {
enableSubstitutionForAsyncMethodsWithSuper();
+ if (ts.hasEntries(capturedSuperProperties)) {
var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
- ts.addStatementsAfterPrologue(statements, [variableStatement]);
+ ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
+ }
}
var block = ts.createBlock(statements, /*multiLine*/ true);
ts.setTextRange(block, node.body);
@@ -69605,8 +70542,10 @@
}
}
enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
+ if (!isArrowFunction) {
capturedSuperProperties = savedCapturedSuperProperties;
hasSuperElementAccess = savedHasSuperElementAccess;
+ }
return result;
}
function transformAsyncFunctionBodyWorker(body, start) {
@@ -69759,7 +70698,7 @@
/* typeParameters */ undefined,
/* parameters */ [],
/* type */ undefined,
- /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name))));
+ /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
if (hasBinding) {
getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(
/* modifiers */ undefined,
@@ -69774,7 +70713,7 @@
/* initializer */ undefined)
],
/* type */ undefined,
- /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v")))));
+ /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v")))));
}
accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter)));
});
@@ -69789,14 +70728,14 @@
], 2 /* Const */));
}
ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
- var awaiterHelper = {
+ ts.awaiterHelper = {
name: "typescript:awaiter",
scoped: false,
priority: 5,
text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
};
function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
- context.requestEmitHelper(awaiterHelper);
+ context.requestEmitHelper(ts.awaiterHelper);
var generatorFunc = ts.createFunctionExpression(
/*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */),
/*name*/ undefined,
@@ -69832,7 +70771,7 @@
/** Enables substitutions for async methods with `super` calls. */
ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
})(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
- function transformESNext(context) {
+ function transformES2018(context) {
var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
var resolver = context.getEmitResolver();
var compilerOptions = context.getCompilerOptions();
@@ -69872,7 +70811,7 @@
return node;
}
function visitorWorker(node, noDestructuringValue) {
- if ((node.transformFlags & 8 /* ContainsESNext */) === 0) {
+ if ((node.transformFlags & 16 /* ContainsES2018 */) === 0) {
return node;
}
switch (node.kind) {
@@ -69916,8 +70855,6 @@
return visitExpressionStatement(node);
case 195 /* ParenthesizedExpression */:
return visitParenthesizedExpression(node, noDestructuringValue);
- case 274 /* CatchClause */:
- return visitCatchClause(node);
case 189 /* PropertyAccessExpression */:
if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) {
capturedSuperProperties.set(node.name.escapedText, true);
@@ -69992,7 +70929,7 @@
return objects;
}
function visitObjectLiteralExpression(node) {
- if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
// spread elements emit like so:
// non-spread elements are chunked together into object literals, and then all are passed to __assign:
// { a, ...o, b } => __assign({a}, o, {b});
@@ -70012,19 +70949,13 @@
function visitParenthesizedExpression(node, noDestructuringValue) {
return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
}
- function visitCatchClause(node) {
- if (!node.variableDeclaration) {
- return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
- }
- return ts.visitEachChild(node, visitor, context);
- }
/**
* Visits a BinaryExpression that contains a destructuring assignment.
*
* @param node A BinaryExpression node.
*/
function visitBinaryExpression(node, noDestructuringValue) {
- if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
}
else if (node.operatorToken.kind === 27 /* CommaToken */) {
@@ -70039,7 +70970,7 @@
*/
function visitVariableDeclaration(node) {
// If we are here it is because the name contains a binding pattern with a rest somewhere in it.
- if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (ts.isBindingPattern(node.name) && node.name.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */);
}
return ts.visitEachChild(node, visitor, context);
@@ -70056,7 +70987,7 @@
* @param node A ForOfStatement.
*/
function visitForOfStatement(node, outermostLabeledStatement) {
- if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.initializer.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
node = transformForOfStatementWithObjectRest(node);
}
if (node.awaitModifier) {
@@ -70153,7 +71084,7 @@
]));
}
function visitParameter(node) {
- if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
// Binding patterns are converted into a generated name and are
// evaluated inside the function body.
return ts.updateParameter(node,
@@ -70266,10 +71197,10 @@
enableSubstitutionForAsyncMethodsWithSuper();
var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
- ts.addStatementsAfterPrologue(statements, [variableStatement]);
+ ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
}
statements.push(returnStatement);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var block = ts.updateBlock(node.body, statements);
if (emitSuperHelpers && hasSuperElementAccess) {
if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
@@ -70295,7 +71226,7 @@
var leadingStatements = endLexicalEnvironment();
if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
- ts.addStatementsAfterPrologue(statements, leadingStatements);
+ ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
ts.addRange(statements, block.statements.slice(statementOffset));
return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
}
@@ -70304,7 +71235,7 @@
function appendObjectRestAssignmentsIfNeeded(statements, node) {
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
- if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) {
+ if (parameter.transformFlags & 8192 /* ContainsObjectRestOrSpread */) {
var temp = ts.getGeneratedNameForNode(parameter);
var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp,
/*doNotRecordTempVariablesInLine*/ false,
@@ -70435,8 +71366,8 @@
}
}
}
- ts.transformESNext = transformESNext;
- var assignHelper = {
+ ts.transformES2018 = transformES2018;
+ ts.assignHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
@@ -70447,28 +71378,28 @@
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"),
/*typeArguments*/ undefined, attributesSegments);
}
- context.requestEmitHelper(assignHelper);
+ context.requestEmitHelper(ts.assignHelper);
return ts.createCall(ts.getHelperName("__assign"),
/*typeArguments*/ undefined, attributesSegments);
}
ts.createAssignHelper = createAssignHelper;
- var awaitHelper = {
+ ts.awaitHelper = {
name: "typescript:await",
scoped: false,
text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
};
function createAwaitHelper(context, expression) {
- context.requestEmitHelper(awaitHelper);
+ context.requestEmitHelper(ts.awaitHelper);
return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
}
- var asyncGeneratorHelper = {
+ ts.asyncGeneratorHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
};
function createAsyncGeneratorHelper(context, generatorFunc) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncGeneratorHelper);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncGeneratorHelper);
// Mark this node as originally an async function
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */;
return ts.createCall(ts.getHelperName("__asyncGenerator"),
@@ -70478,24 +71409,24 @@
generatorFunc
]);
}
- var asyncDelegator = {
+ ts.asyncDelegator = {
name: "typescript:asyncDelegator",
scoped: false,
text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
};
function createAsyncDelegatorHelper(context, expression, location) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncDelegator);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncDelegator);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"),
/*typeArguments*/ undefined, [expression]), location);
}
- var asyncValues = {
+ ts.asyncValues = {
name: "typescript:asyncValues",
scoped: false,
text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
};
function createAsyncValuesHelper(context, expression, location) {
- context.requestEmitHelper(asyncValues);
+ context.requestEmitHelper(ts.asyncValues);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"),
/*typeArguments*/ undefined, [expression]), location);
}
@@ -70503,6 +71434,60 @@
/*@internal*/
var ts;
(function (ts) {
+ function transformES2019(context) {
+ return ts.chainBundle(transformSourceFile);
+ function transformSourceFile(node) {
+ if (node.isDeclarationFile) {
+ return node;
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitor(node) {
+ if ((node.transformFlags & 8 /* ContainsES2019 */) === 0) {
+ return node;
+ }
+ switch (node.kind) {
+ case 274 /* CatchClause */:
+ return visitCatchClause(node);
+ default:
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ function visitCatchClause(node) {
+ if (!node.variableDeclaration) {
+ return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ ts.transformES2019 = transformES2019;
+})(ts || (ts = {}));
+/*@internal*/
+var ts;
+(function (ts) {
+ function transformESNext(context) {
+ return ts.chainBundle(transformSourceFile);
+ function transformSourceFile(node) {
+ if (node.isDeclarationFile) {
+ return node;
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitor(node) {
+ if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
+ return node;
+ }
+ switch (node.kind) {
+ default:
+ return ts.visitEachChild(node, visitor, context);
+ }
+ }
+ }
+ ts.transformESNext = transformESNext;
+})(ts || (ts = {}));
+/*@internal*/
+var ts;
+(function (ts) {
function transformJsx(context) {
var compilerOptions = context.getCompilerOptions();
var currentSourceFile;
@@ -70522,7 +71507,7 @@
return visited;
}
function visitor(node) {
- if (node.transformFlags & 4 /* ContainsJsx */) {
+ if (node.transformFlags & 2 /* ContainsJsx */) {
return visitorWorker(node);
}
else {
@@ -70639,7 +71624,7 @@
}
}
function visitJsxText(node) {
- var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, /*includeTrivia*/ true));
+ var fixed = fixupWhitespaceAndDecodeEntities(node.text);
return fixed === undefined ? undefined : ts.createLiteral(fixed);
}
/**
@@ -71024,7 +72009,7 @@
return ts.visitEachChild(node, visitor, context);
}
function visitor(node) {
- if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) {
+ if ((node.transformFlags & 64 /* ContainsES2016 */) === 0) {
return node;
}
switch (node.kind) {
@@ -71104,30 +72089,6 @@
Jump[Jump["Continue"] = 4] = "Continue";
Jump[Jump["Return"] = 8] = "Return";
})(Jump || (Jump = {}));
- var SuperCaptureResult;
- (function (SuperCaptureResult) {
- /**
- * A capture may have been added for calls to 'super', but
- * the caller should emit subsequent statements normally.
- */
- SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement";
- /**
- * A call to 'super()' got replaced with a capturing statement like:
- *
- * var _this = _super.call(...) || this;
- *
- * Callers should skip the current statement.
- */
- SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture";
- /**
- * A call to 'super()' got replaced with a capturing statement like:
- *
- * return _super.call(...) || this;
- *
- * Callers should skip the current statement and avoid any returns of '_this'.
- */
- SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn";
- })(SuperCaptureResult || (SuperCaptureResult = {}));
// Facts we track as we traverse the tree
var HierarchyFacts;
(function (HierarchyFacts) {
@@ -71148,12 +72109,12 @@
HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement";
HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement";
HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper";
- HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName";
// NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
+ // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
//
// Ancestor masks
//
- HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
+ HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 8191] = "AncestorFactsMask";
// We are always in *some* kind of block scope, but only specific block-scope containers are
// top-level or Blocks.
HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
@@ -71163,16 +72124,16 @@
HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes";
// Functions, methods, and accessors are both new lexical scopes and new block scopes.
HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
- HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
+ HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 8094] = "FunctionExcludes";
HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
- HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
+ HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 8086] = "AsyncFunctionBodyExcludes";
// Arrow functions are lexically scoped to their container, but are new block scopes.
HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
- HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes";
+ HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 8064] = "ArrowFunctionExcludes";
// Constructors are both new lexical scopes and new block scopes. Constructors are also
// always considered non-static members of a class.
HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
- HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
+ HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 8086] = "ConstructorExcludes";
// 'do' and 'while' statements are not block scopes. We track that the subtree is contained
// within an IterationStatement to indicate whether the embedded statement is an
// IterationStatementBlock.
@@ -71190,19 +72151,17 @@
HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes";
HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes";
- // Computed property names track subtree flags differently than their containing members.
- HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes";
- HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes";
//
// Subtree facts
//
- HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
- HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName";
+ HierarchyFacts[HierarchyFacts["NewTarget"] = 8192] = "NewTarget";
+ HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 16384] = "CapturedLexicalThis";
//
// Subtree masks
//
- HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
- HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask";
+ HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -8192] = "SubtreeFactsMask";
+ HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
+ HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 24576] = "FunctionSubtreeExcludes";
})(HierarchyFacts || (HierarchyFacts = {}));
function transformES2015(context) {
var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
@@ -71251,7 +72210,7 @@
*/
function enterSubtree(excludeFacts, includeFacts) {
var ancestorFacts = hierarchyFacts;
- hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 8191 /* AncestorFactsMask */;
return ancestorFacts;
}
/**
@@ -71262,7 +72221,7 @@
* @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
*/
function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
- hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -8192 /* SubtreeFactsMask */ | ancestorFacts;
}
function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0
@@ -71284,12 +72243,6 @@
return node;
}
}
- function functionBodyVisitor(node) {
- if (shouldVisitNode(node)) {
- return visitBlock(node, /*isFunctionBody*/ true);
- }
- return node;
- }
function callExpressionVisitor(node) {
if (node.kind === 98 /* SuperKeyword */) {
return visitSuperKeyword(/*isExpressionOfCall*/ true);
@@ -71396,18 +72349,19 @@
}
function visitSourceFile(node) {
var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
+ var prologue = [];
var statements = [];
startLexicalEnvironment();
- var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false);
- addCaptureThisForNodeIfNeeded(statements, node);
- statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor);
+ var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false);
+ statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor);
ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
if (taggedTemplateStringDeclarations) {
statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureThisForNodeIfNeeded(prologue, node);
exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
- return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
+ return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
}
function visitSwitchStatement(node) {
if (convertedLoopState !== undefined) {
@@ -71447,6 +72401,9 @@
return ts.visitEachChild(node, visitor, context);
}
function visitThisKeyword(node) {
+ if (hierarchyFacts & 2 /* ArrowFunction */) {
+ hierarchyFacts |= 16384 /* CapturedLexicalThis */;
+ }
if (convertedLoopState) {
if (hierarchyFacts & 2 /* ArrowFunction */) {
// if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
@@ -71660,7 +72617,7 @@
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
ts.setEmitFlags(block, 1536 /* NoComments */);
return block;
@@ -71688,7 +72645,7 @@
function addConstructor(statements, node, extendsClauseElement) {
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
+ var ancestorFacts = enterSubtree(8086 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
var constructor = ts.getFirstConstructorWithBody(node);
var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
var constructorFunction = ts.createFunctionDeclaration(
@@ -71702,7 +72659,7 @@
ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
}
statements.push(constructorFunction);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
}
/**
@@ -71721,6 +72678,24 @@
return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
|| [];
}
+ function createDefaultConstructorBody(node, isDerivedClass) {
+ // We must be here because the user didn't write a constructor
+ // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
+ // If that's the case we can just immediately return the result of a 'super()' call.
+ var statements = [];
+ resumeLexicalEnvironment();
+ ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
+ if (isDerivedClass) {
+ // return _super !== null && _super.apply(this, arguments) || this;
+ statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
+ }
+ var statementsArray = ts.createNodeArray(statements);
+ ts.setTextRange(statementsArray, node.members);
+ var block = ts.createBlock(statementsArray, /*multiLine*/ true);
+ ts.setTextRange(block, node);
+ ts.setEmitFlags(block, 1536 /* NoComments */);
+ return block;
+ }
/**
* Transforms the body of a constructor declaration of a class.
*
@@ -71731,59 +72706,137 @@
* synthesized `super` call.
*/
function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
+ // determine whether the class is known syntactically to be a derived class (e.g. a
+ // class that extends a value that is not syntactically known to be `null`).
+ var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */;
+ // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
+ // representation:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base { }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // return _super.apply(this, arguments) || this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ if (!constructor)
+ return createDefaultConstructorBody(node, isDerivedClass);
+ // The prologue will contain all leading standard and custom prologue statements added by this transform
+ var prologue = [];
var statements = [];
resumeLexicalEnvironment();
- var statementOffset = -1;
- if (hasSynthesizedSuper) {
// If a super call has already been synthesized,
// we're going to assume that we should just transform everything after that.
// The assumption is that no prior step in the pipeline has added any prologue directives.
- statementOffset = 0;
- }
- else if (constructor) {
- statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false);
- }
- if (constructor) {
+ var statementOffset = 0;
+ if (!hasSynthesizedSuper)
+ statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false);
addDefaultValueAssignmentsIfNeeded(statements, constructor);
addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
- if (!hasSynthesizedSuper) {
- // If no super call has been synthesized, emit custom prologue directives.
+ if (!hasSynthesizedSuper)
statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
+ // If the first statement is a call to `super()`, visit the statement directly
+ var superCallExpression;
+ if (hasSynthesizedSuper) {
+ superCallExpression = createDefaultSuperCallOrThis();
}
- ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!");
+ else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
+ var firstStatement = constructor.body.statements[statementOffset];
+ if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
+ superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
}
- // determine whether the class is known syntactically to be a derived class (e.g. a
- // class that extends a value that is not syntactically known to be `null`).
- var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */;
- var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset);
- // The last statement expression was replaced. Skip it.
- if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) {
- statementOffset++;
}
- if (constructor) {
- if (superCaptureStatus === 1 /* ReplaceSuperCapture */) {
+ if (superCallExpression) {
hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */;
+ statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
}
+ // visit the remaining statements
ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
+ if (isDerivedClass) {
+ if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 2048 /* ContainsLexicalThis */)) {
+ // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
+ // following representation:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base {
+ // constructor() {
+ // super("foo");
+ // }
+ // }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // return _super.call(this, "foo") || this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
+ var returnStatement = ts.createReturn(superCallExpression);
+ ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
+ ts.setEmitFlags(superCall, 1536 /* NoComments */);
+ statements.push(returnStatement);
}
- // Return `_this` unless we're sure enough that it would be pointless to add a return statement.
- // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return.
- if (isDerivedClass
- && superCaptureStatus !== 2 /* ReplaceWithReturn */
- && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) {
+ else {
+ // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
+ //
+ // ```
+ // // es2015 (source)
+ // class C extends Base {
+ // constructor() {
+ // super("foo");
+ // this.x = 1;
+ // }
+ // }
+ //
+ // // es5 (transformed)
+ // var C = (function (_super) {
+ // function C() {
+ // var _this = _super.call(this, "foo") || this;
+ // _this.x = 1;
+ // return _this;
+ // }
+ // return C;
+ // })(Base);
+ // ```
+ // Since the `super()` call was the first statement, we insert the `this` capturing call to
+ // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
+ insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
+ if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
}
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
- if (constructor) {
- prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false);
}
- var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements),
- /*location*/ constructor ? constructor.body.statements : node.members),
- /*multiLine*/ true);
- ts.setTextRange(block, constructor ? constructor.body : node);
- if (!constructor) {
- ts.setEmitFlags(block, 1536 /* NoComments */);
}
+ else {
+ // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
+ // captured when necessitated by an arrow function capturing the lexical `this`:
+ //
+ // ```
+ // // es2015
+ // class C {}
+ //
+ // // es5
+ // var C = (function () {
+ // function C() {
+ // }
+ // return C;
+ // })();
+ // ```
+ insertCaptureThisForNodeIfNeeded(prologue, constructor);
+ }
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)),
+ /*location*/ constructor.body.statements),
+ /*multiLine*/ true);
+ ts.setTextRange(block, constructor.body);
return block;
}
/**
@@ -71813,83 +72866,6 @@
}
return false;
}
- /**
- * Declares a `_this` variable for derived classes and for when arrow functions capture `this`.
- *
- * @returns The new statement offset into the `statements` array.
- */
- function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) {
- // If this isn't a derived class, just capture 'this' for arrow functions if necessary.
- if (!isDerivedClass) {
- if (ctor) {
- addCaptureThisForNodeIfNeeded(statements, ctor);
- }
- return 0 /* NoReplacement */;
- }
- // We must be here because the user didn't write a constructor
- // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
- // If that's the case we can just immediately return the result of a 'super()' call.
- if (!ctor) {
- statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
- return 2 /* ReplaceWithReturn */;
- }
- // The constructor exists, but it and the 'super()' call it contains were generated
- // for something like property initializers.
- // Create a captured '_this' variable and assume it will subsequently be used.
- if (hasSynthesizedSuper) {
- captureThisForNode(statements, ctor, createDefaultSuperCallOrThis());
- enableSubstitutionsForCapturedThis();
- return 1 /* ReplaceSuperCapture */;
- }
- // Most of the time, a 'super' call will be the first real statement in a constructor body.
- // In these cases, we'd like to transform these into a *single* statement instead of a declaration
- // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer,
- // we'd get:
- //
- // var _this;
- // _this = _super.call(...) || this;
- //
- // instead of
- //
- // var _this = _super.call(...) || this;
- //
- // Additionally, if the 'super()' call is the last statement, we should just avoid capturing
- // entirely and immediately return the result like so:
- //
- // return _super.call(...) || this;
- //
- var firstStatement;
- var superCallExpression;
- var ctorStatements = ctor.body.statements;
- if (statementOffset < ctorStatements.length) {
- firstStatement = ctorStatements[statementOffset];
- if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) {
- superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
- }
- }
- // Return the result if we have an immediate super() call on the last statement,
- // but only if the constructor itself doesn't use 'this' elsewhere.
- if (superCallExpression
- && statementOffset === ctorStatements.length - 1
- && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) {
- var returnStatement = ts.createReturn(superCallExpression);
- if (superCallExpression.kind !== 204 /* BinaryExpression */
- || superCallExpression.left.kind !== 191 /* 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.
- ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */)));
- statements.push(returnStatement);
- return 2 /* ReplaceWithReturn */;
- }
- // Perform the capture.
- 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 */;
- }
- return 0 /* NoReplacement */;
- }
function createActualThis() {
return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
}
@@ -71935,14 +72911,9 @@
return node;
}
}
- /**
- * Gets a value indicating whether we need to add default value assignments for a
- * function-like node.
- *
- * @param node A function-like node.
- */
- function shouldAddDefaultValueAssignments(node) {
- return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0;
+ function hasDefaultValueOrBindingPattern(node) {
+ return node.initializer !== undefined
+ || ts.isBindingPattern(node.name);
}
/**
* Adds statements to the body of a function-like node if it contains parameters with
@@ -71952,9 +72923,10 @@
* @param node A function-like node.
*/
function addDefaultValueAssignmentsIfNeeded(statements, node) {
- if (!shouldAddDefaultValueAssignments(node)) {
- return;
+ if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
+ return false;
}
+ var added = false;
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
@@ -71964,12 +72936,14 @@
continue;
}
if (ts.isBindingPattern(name)) {
- addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer);
+ added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
}
else if (initializer) {
- addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
+ insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
+ added = true;
}
}
+ return added;
}
/**
* Adds statements to the body of a function-like node for parameters with binding patterns
@@ -71979,18 +72953,20 @@
* @param name The name of the parameter.
* @param initializer The initializer for the parameter.
*/
- function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
- var temp = ts.getGeneratedNameForNode(parameter);
+ function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
// In cases where a binding pattern is simply '[]' or '{}',
// we usually don't want to emit a var declaration; however, in the presence
// of an initializer, we must emit that expression to preserve side effects.
if (name.elements.length > 0) {
- statements.push(ts.setEmitFlags(ts.createVariableStatement(
- /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */));
+ ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(
+ /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
+ return true;
}
else if (initializer) {
- statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
+ ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
+ return true;
}
+ return false;
}
/**
* Adds statements to the body of a function-like node for parameters with initializers.
@@ -72000,7 +72976,7 @@
* @param name The name of the parameter.
* @param initializer The initializer for the parameter.
*/
- function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
+ function insertDefaultValueAssignmentForInitializer(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.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 */))
@@ -72008,7 +72984,7 @@
ts.startOnNewLine(statement);
ts.setTextRange(statement, parameter);
ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
- statements.push(statement);
+ ts.insertStatementAfterCustomPrologue(statements, statement);
}
/**
* Gets a value indicating whether we need to add statements to handle a rest parameter.
@@ -72031,9 +73007,10 @@
* synthesized call to `super`
*/
function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
+ var prologueStatements = [];
var parameter = ts.lastOrUndefined(node.parameters);
if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
- return;
+ return false;
}
// `declarationName` is the name of the local declaration for the parameter.
var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined);
@@ -72043,7 +73020,7 @@
var restIndex = node.parameters.length - 1;
var temp = ts.createLoopVariable();
// var param = [];
- statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
+ prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList([
ts.createVariableDeclaration(declarationName,
/*type*/ undefined, ts.createArrayLiteral([]))
@@ -72062,25 +73039,30 @@
]));
ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
ts.startOnNewLine(forStatement);
- statements.push(forStatement);
+ prologueStatements.push(forStatement);
if (parameter.name.kind !== 72 /* Identifier */) {
// do the actual destructuring of the rest parameter if necessary
- statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
+ prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
}
+ ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
+ return true;
}
/**
* Adds a statement to capture the `this` of a function declaration if it is needed.
+ * NOTE: This must be executed *after* the subtree has been visited.
*
* @param statements The statements for the new function body.
* @param node A node.
*/
- function addCaptureThisForNodeIfNeeded(statements, node) {
- if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) {
- captureThisForNode(statements, node, ts.createThis());
+ function insertCaptureThisForNodeIfNeeded(statements, node) {
+ if (hierarchyFacts & 16384 /* CapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) {
+ insertCaptureThisForNode(statements, node, ts.createThis());
+ return true;
}
+ return false;
}
- function captureThisForNode(statements, node, initializer) {
+ function insertCaptureThisForNode(statements, node, initializer) {
enableSubstitutionsForCapturedThis();
var captureThisStatement = ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList([
@@ -72089,10 +73071,10 @@
]));
ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
ts.setSourceMapRange(captureThisStatement, node);
- statements.push(captureThisStatement);
+ ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
}
- function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
- if (hierarchyFacts & 16384 /* NewTarget */) {
+ function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
+ if (hierarchyFacts & 8192 /* NewTarget */) {
var newTarget = void 0;
switch (node.kind) {
case 197 /* ArrowFunction */:
@@ -72123,10 +73105,11 @@
ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"),
/*type*/ undefined, newTarget)
]));
+ ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
if (copyOnWrite) {
- return [captureNewTargetStatement].concat(statements);
+ statements = statements.slice();
}
- statements.unshift(captureNewTargetStatement);
+ ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
}
return statements;
}
@@ -72178,7 +73161,6 @@
* @param member The MethodDeclaration node.
*/
function transformClassMethodDeclarationToStatement(receiver, member, container) {
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
var commentRange = ts.getCommentRange(member);
var sourceMapRange = ts.getSourceMapRange(member);
var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name);
@@ -72193,7 +73175,6 @@
// No source map should be emitted for this statement to align with the
// old emitter.
ts.setEmitFlags(statement, 48 /* NoSourceMap */);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return statement;
}
/**
@@ -72219,7 +73200,6 @@
*/
function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
// To align with source maps in the old emitter, the receiver and property name
// arguments are both mapped contiguously to the accessor name.
var target = ts.getMutableClone(receiver);
@@ -72255,7 +73235,6 @@
if (startsOnNewLine) {
ts.startOnNewLine(call);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return call;
}
/**
@@ -72264,12 +73243,12 @@
* @param node An ArrowFunction node.
*/
function visitArrowFunction(node) {
- if (node.transformFlags & 8192 /* ContainsLexicalThis */) {
- enableSubstitutionsForCapturedThis();
+ if (node.transformFlags & 2048 /* ContainsLexicalThis */) {
+ hierarchyFacts |= 16384 /* CapturedLexicalThis */;
}
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
+ var ancestorFacts = enterSubtree(8064 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
var func = ts.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
@@ -72279,7 +73258,11 @@
ts.setTextRange(func, node);
ts.setOriginalNode(func, node);
ts.setEmitFlags(func, 8 /* CapturesThis */);
- exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
+ if (hierarchyFacts & 16384 /* CapturedLexicalThis */) {
+ enableSubstitutionsForCapturedThis();
+ }
+ // If an arrow function contains
+ exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return func;
}
@@ -72290,18 +73273,16 @@
*/
function visitFunctionExpression(node) {
var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
- ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
- : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ ? enterSubtree(8086 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
+ : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & 64 /* ES2015 */
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
- var name = hierarchyFacts & 16384 /* NewTarget */
+ var body = transformFunctionBody(node);
+ var name = hierarchyFacts & 8192 /* NewTarget */
? ts.getLocalName(node)
: node.name;
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.updateFunctionExpression(node,
/*modifiers*/ undefined, node.asteriskToken, name,
@@ -72316,15 +73297,13 @@
function visitFunctionDeclaration(node) {
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & 64 /* ES2015 */
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
- var name = hierarchyFacts & 16384 /* NewTarget */
+ var body = transformFunctionBody(node);
+ var name = hierarchyFacts & 8192 /* NewTarget */
? ts.getLocalName(node)
: node.name;
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.updateFunctionDeclaration(node,
/*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name,
@@ -72342,14 +73321,14 @@
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
- ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
- : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ ? enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
+ : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var parameters = ts.visitParameterList(node.parameters, visitor, context);
var body = transformFunctionBody(node);
- if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) {
+ if (hierarchyFacts & 8192 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) {
name = ts.getGeneratedNameForNode(node);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
/*modifiers*/ undefined, node.asteriskToken, name,
@@ -72367,7 +73346,7 @@
var singleLine = false; // indicates whether the block *may* be emitted as a single line
var statementsLocation;
var closeBraceLocation;
- var leadingStatements = [];
+ var prologue = [];
var statements = [];
var body = node.body;
var statementOffset;
@@ -72375,14 +73354,13 @@
if (ts.isBlock(body)) {
// ensureUseStrict is false because no new prologue-directive should be added.
// addStandardPrologue will put already-existing directives at the beginning of the target statement-array
- statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false);
+ statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false);
}
- addCaptureThisForNodeIfNeeded(leadingStatements, node);
- addDefaultValueAssignmentsIfNeeded(leadingStatements, node);
- addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false);
+ multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
+ multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
if (ts.isBlock(body)) {
// addCustomPrologue puts already-existing directives at the beginning of the target statement-array
- statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor);
+ statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
statementsLocation = body.statements;
ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
// If the original body was a multi-line block, this must be a multi-line block.
@@ -72416,14 +73394,19 @@
// source map location for the close brace.
closeBraceLocation = body;
}
- var lexicalEnvironment = context.endLexicalEnvironment();
- ts.addStatementsAfterPrologue(statements, lexicalEnvironment);
- prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false);
+ ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
+ insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
+ insertCaptureThisForNodeIfNeeded(prologue, node);
// If we added any final generated statements, this must be a multi-line block
- if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) {
+ if (ts.some(prologue)) {
multiLine = true;
}
- var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine);
+ statements.unshift.apply(statements, prologue);
+ if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
+ // no changes were made, preserve the tree
+ return body;
+ }
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
ts.setTextRange(block, node.body);
if (!multiLine && singleLine) {
ts.setEmitFlags(block, 1 /* SingleLine */);
@@ -72434,11 +73417,6 @@
ts.setOriginalNode(block, node.body);
return block;
}
- function visitFunctionBodyDownLevel(node) {
- var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context);
- return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)),
- /*location*/ updated.statements));
- }
function visitBlock(node, isFunctionBody) {
if (isFunctionBody) {
// A function body is not a block scope.
@@ -72543,7 +73521,7 @@
* @param node A VariableDeclarationList node.
*/
function visitVariableDeclarationList(node) {
- if (node.transformFlags & 64 /* ES2015 */) {
+ if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 65536 /* ContainsBindingPattern */) {
if (node.flags & 3 /* BlockScoped */) {
enableSubstitutionsForBlockScopedBindings();
}
@@ -72556,7 +73534,7 @@
ts.setCommentRange(declarationList, node);
// If the first or last declaration is a binding pattern, we need to modify
// the source map range for the declaration list.
- if (node.transformFlags & 2097152 /* ContainsBindingPattern */
+ if (node.transformFlags & 65536 /* ContainsBindingPattern */
&& (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
}
@@ -72878,7 +73856,7 @@
var numInitialPropertiesWithoutYield = numProperties;
for (var i = 0; i < numProperties; i++) {
var property = properties[i];
- if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
+ if ((property.transformFlags & 131072 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
&& i < numInitialPropertiesWithoutYield) {
numInitialPropertiesWithoutYield = i;
}
@@ -73154,7 +74132,7 @@
*/
function createFunctionForInitializerOfForStatement(node, currentState) {
var functionName = ts.createUniqueName("_loop_init");
- var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ var containsYield = (node.initializer.transformFlags & 131072 /* ContainsYield */) !== 0;
var emitFlags = 0 /* None */;
if (currentState.containsLexicalThis)
emitFlags |= 8 /* CapturesThis */;
@@ -73259,11 +74237,11 @@
statements.push(statement);
}
copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
- ts.addStatementsAfterPrologue(statements, lexicalEnvironment);
+ ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
var loopBody = ts.createBlock(statements, /*multiLine*/ true);
if (ts.isBlock(statement))
ts.setOriginalNode(loopBody, statement);
- var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ var containsYield = (node.statement.transformFlags & 131072 /* ContainsYield */) !== 0;
var emitFlags = 0;
if (currentState.containsLexicalThis)
emitFlags |= 8 /* CapturesThis */;
@@ -73495,13 +74473,11 @@
* @param receiver The receiver for the assignment.
*/
function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
- var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
ts.setTextRange(expression, method);
if (startsOnNewLine) {
ts.startOnNewLine(expression);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return expression;
}
function visitCatchClause(node) {
@@ -73553,19 +74529,17 @@
ts.Debug.assert(!ts.isComputedPropertyName(node.name));
var savedConvertedLoopState = convertedLoopState;
convertedLoopState = undefined;
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */);
var updated;
var parameters = ts.visitParameterList(node.parameters, visitor, context);
- var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */)
- ? transformFunctionBody(node)
- : visitFunctionBodyDownLevel(node);
+ var body = transformFunctionBody(node);
if (node.kind === 158 /* GetAccessor */) {
updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
}
else {
updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
}
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */);
convertedLoopState = savedConvertedLoopState;
return updated;
}
@@ -73579,10 +74553,7 @@
/*location*/ node);
}
function visitComputedPropertyName(node) {
- var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */);
- var updated = ts.visitEachChild(node, visitor, context);
- exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */);
- return updated;
+ return ts.visitEachChild(node, visitor, context);
}
/**
* Visits a YieldExpression node.
@@ -73599,7 +74570,7 @@
* @param node An ArrayLiteralExpression node.
*/
function visitArrayLiteralExpression(node) {
- if (node.transformFlags & 64 /* ES2015 */) {
+ if (ts.some(node.elements, ts.isSpreadElement)) {
// We are here because we contain a SpreadElementExpression.
return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
}
@@ -73614,7 +74585,10 @@
if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
return visitTypeScriptClassWrapper(node);
}
- if (node.transformFlags & 64 /* ES2015 */) {
+ var expression = ts.skipOuterExpressions(node.expression);
+ if (expression.kind === 98 /* SuperKeyword */ ||
+ ts.isSuperProperty(expression) ||
+ ts.some(node.arguments, ts.isSpreadElement)) {
return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
}
return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression),
@@ -73735,7 +74709,7 @@
function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
// We are here either because SuperKeyword was used somewhere in the expression, or
// because we contain a SpreadElementExpression.
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */ ||
+ if (node.transformFlags & 4096 /* ContainsRestOrSpread */ ||
node.expression.kind === 98 /* SuperKeyword */ ||
ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
@@ -73743,7 +74717,7 @@
ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
}
var resultingCall = void 0;
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */) {
+ if (node.transformFlags & 4096 /* ContainsRestOrSpread */) {
// [source]
// f(...a, b)
// x.m(...a, b)
@@ -73757,7 +74731,7 @@
// _super.apply(this, a.concat([b]))
// _super.m.apply(this, a.concat([b]))
// _super.prototype.m.apply(this, a.concat([b]))
- resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
+ resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
}
else {
// [source]
@@ -73769,13 +74743,11 @@
// _super.call(this, a)
// _super.m.call(this, a)
// _super.prototype.m.call(this, a)
- resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
+ resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
/*location*/ node);
}
if (node.expression.kind === 98 /* SuperKeyword */) {
- var actualThis = ts.createThis();
- ts.setEmitFlags(actualThis, 4 /* NoSubstitution */);
- var initializer = ts.createLogicalOr(resultingCall, actualThis);
+ var initializer = ts.createLogicalOr(resultingCall, createActualThis());
resultingCall = assignToCapturedThis
? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
: initializer;
@@ -73790,7 +74762,7 @@
* @param node A NewExpression node.
*/
function visitNewExpression(node) {
- if (node.transformFlags & 131072 /* ContainsRestOrSpread */) {
+ if (ts.some(node.arguments, ts.isSpreadElement)) {
// We are here because we contain a SpreadElementExpression.
// [source]
// new C(...a)
@@ -74053,12 +75025,7 @@
}
function visitMetaProperty(node) {
if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") {
- if (hierarchyFacts & 8192 /* ComputedPropertyName */) {
- hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */;
- }
- else {
- hierarchyFacts |= 16384 /* NewTarget */;
- }
+ hierarchyFacts |= 8192 /* NewTarget */;
return ts.createFileLevelUniqueName("_newTarget");
}
return node;
@@ -74073,7 +75040,7 @@
function onEmitNode(hint, node, emitCallback) {
if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
// If we are tracking a captured `this`, keep track of the enclosing function.
- var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
+ var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
: 65 /* FunctionIncludes */);
previousOnEmitNode(hint, node, emitCallback);
@@ -74253,7 +75220,7 @@
}
ts.transformES2015 = transformES2015;
function createExtendsHelper(context, name) {
- context.requestEmitHelper(extendsHelper);
+ context.requestEmitHelper(ts.extendsHelper);
return ts.createCall(ts.getHelperName("__extends"),
/*typeArguments*/ undefined, [
name,
@@ -74261,20 +75228,20 @@
]);
}
function createTemplateObjectHelper(context, cooked, raw) {
- context.requestEmitHelper(templateObjectHelper);
+ context.requestEmitHelper(ts.templateObjectHelper);
return ts.createCall(ts.getHelperName("__makeTemplateObject"),
/*typeArguments*/ undefined, [
cooked,
raw
]);
}
- var extendsHelper = {
+ ts.extendsHelper = {
name: "typescript:extends",
scoped: false,
priority: 0,
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 = {
+ ts.templateObjectHelper = {
name: "typescript:makeTemplateObject",
scoped: false,
priority: 0,
@@ -74621,7 +75588,7 @@
var withBlockStack; // A stack containing `with` blocks.
return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
- if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
+ if (node.isDeclarationFile || (node.transformFlags & 256 /* ContainsGenerator */) === 0) {
return node;
}
var visited = ts.visitEachChild(node, visitor, context);
@@ -74641,10 +75608,10 @@
else if (inGeneratorFunctionBody) {
return visitJavaScriptInGeneratorFunctionBody(node);
}
- else if (transformFlags & 256 /* Generator */) {
+ else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
return visitGenerator(node);
}
- else if (transformFlags & 512 /* ContainsGenerator */) {
+ else if (transformFlags & 256 /* ContainsGenerator */) {
return ts.visitEachChild(node, visitor, context);
}
else {
@@ -74697,10 +75664,10 @@
case 230 /* ReturnStatement */:
return visitReturnStatement(node);
default:
- if (node.transformFlags & 4194304 /* ContainsYield */) {
+ if (node.transformFlags & 131072 /* ContainsYield */) {
return visitJavaScriptContainingYield(node);
}
- else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) {
+ else if (node.transformFlags & (256 /* ContainsGenerator */ | 262144 /* ContainsHoistedDeclarationOrCompletion */)) {
return ts.visitEachChild(node, visitor, context);
}
else {
@@ -74876,7 +75843,7 @@
var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
transformAndEmitStatements(body.statements, statementOffset);
var buildResult = build();
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
statements.push(ts.createReturn(buildResult));
// Restore previous generator state
inGeneratorFunctionBody = savedInGeneratorFunctionBody;
@@ -74903,7 +75870,7 @@
* @param node The node to visit.
*/
function visitVariableStatement(node) {
- if (node.transformFlags & 4194304 /* ContainsYield */) {
+ if (node.transformFlags & 131072 /* ContainsYield */) {
transformAndEmitVariableDeclarationList(node.declarationList);
return undefined;
}
@@ -75961,7 +76928,7 @@
}
}
function containsYield(node) {
- return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0;
+ return !!node && (node.transformFlags & 131072 /* ContainsYield */) !== 0;
}
function countInitialNodesWithoutYield(nodes) {
var numNodes = nodes.length;
@@ -76968,7 +77935,7 @@
}
ts.transformGenerators = transformGenerators;
function createGeneratorHelper(context, body) {
- context.requestEmitHelper(generatorHelper);
+ context.requestEmitHelper(ts.generatorHelper);
return ts.createCall(ts.getHelperName("__generator"),
/*typeArguments*/ undefined, [ts.createThis(), body]);
}
@@ -77031,7 +77998,7 @@
// entering a finally block.
//
// For examples of how these are used, see the comments in ./transformers/generators.ts
- var generatorHelper = {
+ ts.generatorHelper = {
name: "typescript:generator",
scoped: false,
priority: 6,
@@ -77064,7 +78031,7 @@
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* 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.
@@ -77080,7 +78047,7 @@
function transformSourceFile(node) {
if (node.isDeclarationFile ||
!(ts.isEffectiveExternalModule(node, compilerOptions) ||
- node.transformFlags & 16777216 /* ContainsDynamicImport */ ||
+ node.transformFlags & 524288 /* ContainsDynamicImport */ ||
(ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
return node;
}
@@ -77117,7 +78084,7 @@
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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(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
@@ -77343,7 +78310,7 @@
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
// End the lexical environment for the module body
// and merge any new lexical declarations.
- ts.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var body = ts.createBlock(statements, /*multiLine*/ true);
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
// If we have any `export * from ...` declarations
@@ -77406,9 +78373,9 @@
return visitFunctionDeclaration(node);
case 240 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
@@ -77417,13 +78384,13 @@
function moduleExpressionElementVisitor(node) {
// This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
// as export/import statements are only transformed at the top level of a file.
- if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) {
+ if (!(node.transformFlags & 524288 /* ContainsDynamicImport */) && !(node.transformFlags & 512 /* ContainsDestructuringAssignment */)) {
return node;
}
if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
- else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) {
+ else if (ts.isDestructuringAssignment(node)) {
return visitDestructuringAssignment(node);
}
else {
@@ -77484,7 +78451,7 @@
}
function visitImportCallExpression(node) {
var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
- var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */);
+ var containsLexicalThis = !!(node.transformFlags & 2048 /* ContainsLexicalThis */);
switch (compilerOptions.module) {
case ts.ModuleKind.AMD:
return createImportCallExpressionAMD(argument, containsLexicalThis);
@@ -77566,7 +78533,7 @@
}
var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]);
}
return promise;
@@ -77580,7 +78547,7 @@
var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
}
var func;
@@ -77614,11 +78581,11 @@
return innerExpr;
}
if (ts.getImportNeedsImportStarHelper(node)) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
}
if (ts.getImportNeedsImportDefaultHelper(node)) {
- context.requestEmitHelper(importDefaultHelper);
+ context.requestEmitHelper(ts.importDefaultHelper);
return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
}
return innerExpr;
@@ -78187,7 +79154,7 @@
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
currentSourceFile = node;
currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
noSubstitution = [];
@@ -78275,7 +79242,7 @@
}
if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)),
/*location*/ node);
}
@@ -78401,13 +79368,13 @@
text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
};
// emit helper for `import * as Name from "foo"`
- var importStarHelper = {
+ ts.importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
// emit helper for `import Name from "foo"`
- var importDefaultHelper = {
+ ts.importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
@@ -78430,7 +79397,7 @@
context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols.
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* 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.
@@ -78449,7 +79416,7 @@
* @param node The SourceFile node.
*/
function transformSourceFile(node) {
- if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) {
+ if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 524288 /* ContainsDynamicImport */)) {
return node;
}
var id = ts.getOriginalNodeId(node);
@@ -78615,7 +79582,7 @@
// 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.addStatementsAfterPrologue(statements, endLexicalEnvironment());
+ ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
var moduleObject = ts.createObjectLiteral([
ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
@@ -79000,7 +79967,7 @@
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 === 279 /* SourceFile */
+ && (enclosingBlockScopedContainer.kind === 284 /* SourceFile */
|| (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
}
/**
@@ -79343,9 +80310,9 @@
return visitCatchClause(node);
case 218 /* Block */:
return visitBlock(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -79527,14 +80494,13 @@
* @param node The node to visit.
*/
function destructuringAndImportCallVisitor(node) {
- if (node.transformFlags & 1024 /* DestructuringAssignment */
- && node.kind === 204 /* BinaryExpression */) {
+ if (ts.isDestructuringAssignment(node)) {
return visitDestructuringAssignment(node);
}
else if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
- else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) {
+ else if ((node.transformFlags & 512 /* ContainsDestructuringAssignment */) || (node.transformFlags & 524288 /* ContainsDynamicImport */)) {
return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
}
else {
@@ -79593,7 +80559,7 @@
}
else if (ts.isIdentifier(node)) {
var container = resolver.getReferencedExportContainer(node);
- return container !== undefined && container.kind === 279 /* SourceFile */;
+ return container !== undefined && container.kind === 284 /* SourceFile */;
}
else {
return false;
@@ -79626,7 +80592,7 @@
* @param emitCallback A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
var id = ts.getOriginalNodeId(node);
currentSourceFile = node;
moduleInfo = moduleInfoMap[id];
@@ -79835,7 +80801,7 @@
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
}
exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
@@ -79874,7 +80840,7 @@
var previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- context.enableEmitNotification(279 /* SourceFile */);
+ context.enableEmitNotification(284 /* SourceFile */);
context.enableSubstitution(72 /* Identifier */);
var currentSourceFile;
return ts.chainBundle(transformSourceFile);
@@ -79984,7 +80950,8 @@
ts.isImportEqualsDeclaration(node) ||
ts.isTypeAliasDeclaration(node) ||
ts.isConstructorDeclaration(node) ||
- ts.isIndexSignatureDeclaration(node);
+ ts.isIndexSignatureDeclaration(node) ||
+ ts.isPropertyAccessExpression(node);
}
ts.canProduceDiagnostics = canProduceDiagnostics;
function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
@@ -80058,7 +81025,7 @@
}
ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
function createGetSymbolAccessibilityDiagnosticForNode(node) {
- if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
+ if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
return getVariableDeclarationTypeVisibilityError;
}
else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
@@ -80098,7 +81065,7 @@
}
// This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
// The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
- else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ ||
+ else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 189 /* PropertyAccessExpression */ || node.kind === 153 /* PropertySignature */ ||
(node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
// TODO(jfreeman): Deal with computed properties in error reporting.
if (ts.hasModifier(node, 32 /* Static */)) {
@@ -80303,6 +81270,9 @@
case 241 /* InterfaceDeclaration */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
break;
+ case 181 /* MappedType */:
+ diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
+ break;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
@@ -80386,6 +81356,31 @@
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
+ function hasInternalAnnotation(range, currentSourceFile) {
+ var comment = currentSourceFile.text.substring(range.pos, range.end);
+ return ts.stringContains(comment, "@internal");
+ }
+ function isInternalDeclaration(node, currentSourceFile) {
+ var parseTreeNode = ts.getParseTreeNode(node);
+ if (parseTreeNode && parseTreeNode.kind === 151 /* Parameter */) {
+ var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
+ var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
+ var text = currentSourceFile.text;
+ var commentRanges = previousSibling
+ ? ts.concatenate(
+ // to handle
+ // ... parameters, /* @internal */
+ // public param: string
+ ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
+ : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
+ return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
+ }
+ var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
+ return !!ts.forEach(leadingCommentRanges, function (range) {
+ return hasInternalAnnotation(range, currentSourceFile);
+ });
+ }
+ ts.isInternalDeclaration = isInternalDeclaration;
var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
2048 /* WriteClassExpressionAsTypeLiteral */ |
4096 /* UseTypeOfFunction */ |
@@ -80514,10 +81509,10 @@
}
}
function transformRoot(node) {
- if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
+ if (node.kind === 284 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
}
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
isBundledEmit = true;
refs = ts.createMap();
libs = ts.createMap();
@@ -80547,9 +81542,15 @@
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 === 282 /* InputFiles */) {
- return ts.createUnparsedSourceFile(prepend, "dts");
+ if (prepend.kind === 287 /* InputFiles */) {
+ var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
+ hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
+ collectReferences(sourceFile, refs);
+ recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
+ collectLibs(sourceFile, libs);
+ return sourceFile;
}
+ return prepend;
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -80641,7 +81642,7 @@
}
}
function collectReferences(sourceFile, ret) {
- if (noResolve || ts.isSourceFileJS(sourceFile))
+ if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
return ret;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
@@ -81188,7 +82189,9 @@
if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
return undefined;
}
+ getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker);
+ getSymbolAccessibilityDiagnostic = oldDiag;
var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
});
@@ -81231,7 +82234,7 @@
if (ctor) {
var oldDiag_1 = getSymbolAccessibilityDiagnostic;
parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
- if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */))
+ if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
return;
getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
if (param.name.kind === 72 /* Identifier */) {
@@ -81367,18 +82370,8 @@
}
errorNameNode = undefined;
}
- function hasInternalAnnotation(range) {
- var comment = currentSourceFile.text.substring(range.pos, range.end);
- return ts.stringContains(comment, "@internal");
- }
function shouldStripInternal(node) {
- if (stripInternal && node) {
- var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile);
- if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
- return true;
- }
- }
- return false;
+ return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
}
function isScopeMarker(node) {
return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
@@ -81400,7 +82393,7 @@
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 === 279 /* SourceFile */;
+ var parentIsFile = node.parent.kind === 284 /* SourceFile */;
if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */);
additions = 0 /* None */;
@@ -81569,9 +82562,15 @@
if (jsx === 2 /* React */) {
transformers.push(ts.transformJsx);
}
- if (languageVersion < 6 /* ESNext */) {
+ if (languageVersion < 7 /* ESNext */) {
transformers.push(ts.transformESNext);
}
+ if (languageVersion < 6 /* ES2019 */) {
+ transformers.push(ts.transformES2019);
+ }
+ if (languageVersion < 5 /* ES2018 */) {
+ transformers.push(ts.transformES2018);
+ }
if (languageVersion < 4 /* ES2017 */) {
transformers.push(ts.transformES2017);
}
@@ -81611,7 +82610,7 @@
* @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(312 /* Count */);
+ var enabledSyntaxKindFeatures = new Array(317 /* Count */);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -81871,10 +82870,14 @@
})(ts || (ts = {}));
var ts;
(function (ts) {
- var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
var syntheticParent = { pos: -1, end: -1 };
/*@internal*/
+ function isBuildInfoFile(file) {
+ return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
+ }
+ ts.isBuildInfoFile = isBuildInfoFile;
+ /*@internal*/
/**
* Iterates over the source files that are expected to have an emit output.
*
@@ -81884,13 +82887,14 @@
* 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, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
+ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles, onlyBuildInfo, includeBuildInfo) {
if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; }
var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
+ var prepends = host.getPrependNodes();
+ if (sourceFiles.length || prepends.length) {
+ var bundle = ts.createBundle(sourceFiles, prepends);
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -81898,6 +82902,7 @@
}
}
else {
+ if (!onlyBuildInfo) {
for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
var sourceFile = sourceFiles_1[_a];
var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
@@ -81906,23 +82911,52 @@
}
}
}
+ if (includeBuildInfo) {
+ var buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
+ if (buildInfoPath)
+ return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
+ }
+ }
}
ts.forEachEmittedFile = forEachEmittedFile;
/*@internal*/
+ function getOutputPathForBuildInfo(options) {
+ var configFile = options.configFilePath;
+ if (!configFile || !ts.isIncrementalCompilation(options))
+ return undefined;
+ if (options.tsBuildInfoFile)
+ return options.tsBuildInfoFile;
+ var outPath = options.outFile || options.out;
+ var buildInfoExtensionLess;
+ if (outPath) {
+ buildInfoExtensionLess = ts.removeFileExtension(outPath);
+ }
+ else {
+ var configFileExtensionLess = ts.removeFileExtension(configFile);
+ buildInfoExtensionLess = options.outDir ?
+ options.rootDir ?
+ ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
+ ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
+ configFileExtensionLess;
+ }
+ return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
+ }
+ ts.getOutputPathForBuildInfo = getOutputPathForBuildInfo;
+ /*@internal*/
function getOutputPathsForBundle(options, forceDtsPaths) {
var outPath = options.outFile || options.out;
var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
var declarationMapPath = declarationFilePath && 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 };
+ var buildInfoPath = getOutputPathForBuildInfo(options);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
}
ts.getOutputPathsForBundle = getOutputPathsForBundle;
/*@internal*/
function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
var options = host.getCompilerOptions();
- if (sourceFile.kind === 280 /* Bundle */) {
+ if (sourceFile.kind === 285 /* Bundle */) {
return getOutputPathsForBundle(options, forceDtsPaths);
}
else {
@@ -81936,19 +82970,13 @@
var isJs = ts.isSourceFileJS(sourceFile);
var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
}
}
ts.getOutputPathsFor = getOutputPathsFor;
function getSourceMapFilePath(jsFilePath, options) {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
- function createDefaultBundleInfo() {
- return {
- originalOffset: -1,
- totalLength: -1
- };
- }
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
@@ -81971,9 +82999,91 @@
return ".js" /* Js */;
}
ts.getOutputExtension = getOutputExtension;
+ function rootDirOfOptions(configFile) {
+ return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.assertDefined(configFile.options.configFilePath));
+ }
+ function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
+ return outputDir ?
+ ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
+ inputFileName;
+ }
+ /* @internal */
+ function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
+ ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(inputFileName));
+ return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
+ }
+ ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
+ function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
+ var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
+ var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
+ ".json" /* Json */ :
+ ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
+ ".jsx" /* Jsx */ :
+ ".js" /* Js */);
+ return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.assertDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
+ outputFileName :
+ undefined;
+ }
+ /*@internal*/
+ function getAllProjectOutputs(configFile, ignoreCase) {
+ var outputs;
+ var addOutput = function (path) { return path && (outputs || (outputs = [])).push(path); };
+ if (configFile.options.outFile || configFile.options.out) {
+ var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ addOutput(jsFilePath);
+ addOutput(sourceMapFilePath);
+ addOutput(declarationFilePath);
+ addOutput(declarationMapPath);
+ addOutput(buildInfoPath);
+ }
+ else {
+ for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
+ var inputFileName = _c[_b];
+ if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
+ continue;
+ var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ addOutput(js);
+ if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
+ continue;
+ if (configFile.options.sourceMap) {
+ addOutput(js + ".map");
+ }
+ if (ts.getEmitDeclarations(configFile.options) && ts.hasTSFileExtension(inputFileName)) {
+ var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
+ addOutput(dts);
+ if (configFile.options.declarationMap) {
+ addOutput(dts + ".map");
+ }
+ }
+ }
+ addOutput(getOutputPathForBuildInfo(configFile.options));
+ }
+ return outputs || ts.emptyArray;
+ }
+ ts.getAllProjectOutputs = getAllProjectOutputs;
+ /*@internal*/
+ function getFirstProjectOutput(configFile, ignoreCase) {
+ if (configFile.options.outFile || configFile.options.out) {
+ var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
+ return ts.Debug.assertDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
+ }
+ for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
+ var inputFileName = _b[_a];
+ if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
+ continue;
+ var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
+ if (jsFilePath)
+ return jsFilePath;
+ }
+ var buildInfoPath = getOutputPathForBuildInfo(configFile.options);
+ if (buildInfoPath)
+ return buildInfoPath;
+ return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
+ }
+ ts.getFirstProjectOutput = getFirstProjectOutput;
/*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers, onlyBuildInfo) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -81981,12 +83091,12 @@
var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
var writer = ts.createTextWriter(newLine);
var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit;
- var bundleInfo = createDefaultBundleInfo();
+ var bundleBuildInfo;
var emitSkipped = false;
var exportedModulesFromDeclarationEmit;
// Emit each output file
enter();
- forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles);
+ forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile);
exit();
return {
emitSkipped: emitSkipped,
@@ -81996,9 +83106,16 @@
exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
+ bundleBuildInfo = {
+ commonSourceDirectory: host.getCommonSourceDirectory(),
+ sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return file.fileName; })
+ };
+ }
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
+ emitBuildInfo(bundleBuildInfo, buildInfoPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
if (jsFilePath) {
@@ -82007,8 +83124,8 @@
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
- if (bundleInfoPath) {
- emittedFilesList.push(bundleInfoPath);
+ if (buildInfoPath) {
+ emittedFilesList.push(buildInfoPath);
}
}
if (declarationFilePath) {
@@ -82019,8 +83136,21 @@
}
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
- if (emitOnlyDtsFiles || !jsFilePath) {
+ function emitBuildInfo(bundle, buildInfoPath) {
+ // Write build information if applicable
+ if (!buildInfoPath || targetSourceFile || emitSkipped)
+ return;
+ var program = host.getProgramBuildInfo();
+ if (!bundle && !program)
+ return;
+ if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
+ emitSkipped = true;
+ return;
+ }
+ ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: ts.version }), /*writeByteOrderMark*/ false);
+ }
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
+ if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
return;
}
// Make sure not to write js file and source map file if any of them cannot be written
@@ -82040,6 +83170,7 @@
inlineSourceMap: compilerOptions.inlineSourceMap,
inlineSources: compilerOptions.inlineSources,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ writeBundleFileInfo: !!bundleBuildInfo
};
// Create a printer to print the nodes
var printer = createPrinter(printerOptions, {
@@ -82050,12 +83181,14 @@
substituteNode: transform.substituteNode,
});
ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions);
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
// Clean up emit nodes on parse tree
transform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.js = printer.bundleFileInfo;
}
function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) {
- if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
+ if (!sourceFileOrBundle || !(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
return;
}
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
@@ -82084,6 +83217,8 @@
inlineSourceMap: compilerOptions.inlineSourceMap,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
onlyPrintJsDocStyle: true,
+ writeBundleFileInfo: !!bundleBuildInfo,
+ recordInternalSection: !!bundleBuildInfo
};
var declarationPrinter = createPrinter(printerOptions, {
// resolver hooks
@@ -82096,18 +83231,20 @@
emitSkipped = emitSkipped || declBlocked;
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, {
+ printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
sourceMap: compilerOptions.declarationMap,
sourceRoot: compilerOptions.sourceRoot,
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
- if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) {
+ if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 284 /* SourceFile */) {
var sourceFile = declarationTransform.transformed[0];
exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
}
}
declarationTransform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
}
function collectLinkedAliases(node) {
if (ts.isExportAssignment(node)) {
@@ -82122,16 +83259,16 @@
}
ts.forEachChild(node, collectLinkedAliases);
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) {
- var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined;
- var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined;
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
+ var bundle = sourceFileOrBundle.kind === 285 /* Bundle */ ? sourceFileOrBundle : undefined;
+ var sourceFile = sourceFileOrBundle.kind === 284 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
var sourceMapGenerator;
if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
}
if (bundle) {
- printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator);
+ printer.writeBundle(bundle, writer, sourceMapGenerator);
}
else {
printer.writeFile(sourceFile, writer, sourceMapGenerator);
@@ -82160,18 +83297,12 @@
}
// Write the output file
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
- // Write bundled offset information if applicable
- if (bundleInfoPath) {
- bundleInfo.totalLength = writer.getTextPos();
- ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false);
- }
// Reset state
writer.clear();
- bundleInfo = createDefaultBundleInfo();
}
function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
- && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
+ && (sourceFileOrBundle.kind !== 284 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
}
function getSourceRoot(mapOptions) {
// Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
@@ -82228,6 +83359,167 @@
}
}
ts.emitFiles = emitFiles;
+ /*@internal*/
+ function getBuildInfoText(buildInfo) {
+ return JSON.stringify(buildInfo, undefined, 2);
+ }
+ ts.getBuildInfoText = getBuildInfoText;
+ /*@internal*/
+ function getBuildInfo(buildInfoText) {
+ return JSON.parse(buildInfoText);
+ }
+ ts.getBuildInfo = getBuildInfo;
+ /*@internal*/
+ ts.notImplementedResolver = {
+ hasGlobalName: ts.notImplemented,
+ getReferencedExportContainer: ts.notImplemented,
+ getReferencedImportDeclaration: ts.notImplemented,
+ getReferencedDeclarationWithCollidingName: ts.notImplemented,
+ isDeclarationWithCollidingName: ts.notImplemented,
+ isValueAliasDeclaration: ts.notImplemented,
+ isReferencedAliasDeclaration: ts.notImplemented,
+ isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
+ getNodeCheckFlags: ts.notImplemented,
+ isDeclarationVisible: ts.notImplemented,
+ isLateBound: function (_node) { return false; },
+ collectLinkedAliases: ts.notImplemented,
+ isImplementationOfOverload: ts.notImplemented,
+ isRequiredInitializedParameter: ts.notImplemented,
+ isOptionalUninitializedParameterProperty: ts.notImplemented,
+ isExpandoFunctionDeclaration: ts.notImplemented,
+ getPropertiesOfContainerFunction: ts.notImplemented,
+ createTypeOfDeclaration: ts.notImplemented,
+ createReturnTypeOfSignatureDeclaration: ts.notImplemented,
+ createTypeOfExpression: ts.notImplemented,
+ createLiteralConstValue: ts.notImplemented,
+ isSymbolAccessible: ts.notImplemented,
+ isEntityNameVisible: ts.notImplemented,
+ // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
+ getConstantValue: ts.notImplemented,
+ getReferencedValueDeclaration: ts.notImplemented,
+ getTypeReferenceSerializationKind: ts.notImplemented,
+ isOptionalParameter: ts.notImplemented,
+ moduleExportsSomeValue: ts.notImplemented,
+ isArgumentsLocalBinding: ts.notImplemented,
+ getExternalModuleFileFromDeclaration: ts.notImplemented,
+ getTypeReferenceDirectivesForEntityName: ts.notImplemented,
+ getTypeReferenceDirectivesForSymbol: ts.notImplemented,
+ isLiteralConstDeclaration: ts.notImplemented,
+ getJsxFactoryEntity: ts.notImplemented,
+ getAllAccessorDeclarations: ts.notImplemented,
+ getSymbolOfExternalModuleSpecifier: ts.notImplemented,
+ isBindingCapturedByNode: ts.notImplemented,
+ };
+ function createSourceFilesFromBundleBuildInfo(bundle) {
+ var sourceFiles = bundle.sourceFiles.map(function (fileName) {
+ var sourceFile = ts.createNode(284 /* SourceFile */, 0, 0);
+ sourceFile.fileName = fileName;
+ sourceFile.text = "";
+ sourceFile.statements = ts.createNodeArray();
+ return sourceFile;
+ });
+ var jsBundle = ts.Debug.assertDefined(bundle.js);
+ ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
+ var sourceFile = sourceFiles[prologueInfo.file];
+ sourceFile.text = prologueInfo.text;
+ sourceFile.end = prologueInfo.text.length;
+ sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
+ var statement = ts.createNode(221 /* ExpressionStatement */, directive.pos, directive.end);
+ statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
+ statement.expression.text = directive.expression.text;
+ return statement;
+ }));
+ });
+ return sourceFiles;
+ }
+ /*@internal*/
+ function emitUsingBuildInfo(config, host, getCommandLine) {
+ var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
+ var buildInfoText = host.readFile(ts.Debug.assertDefined(buildInfoPath));
+ if (!buildInfoText)
+ return buildInfoPath;
+ var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath));
+ if (!jsFileText)
+ return jsFilePath;
+ var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
+ // error if no source map or for now if inline sourcemap
+ if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
+ return sourceMapFilePath || "inline sourcemap decoding";
+ // read declaration text
+ var declarationText = declarationFilePath && host.readFile(declarationFilePath);
+ if (declarationFilePath && !declarationText)
+ return declarationFilePath;
+ var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
+ // error if no source map or for now if inline sourcemap
+ if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
+ return declarationMapPath || "inline sourcemap decoding";
+ var buildInfo = getBuildInfo(buildInfoText);
+ if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
+ return buildInfoPath;
+ var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo,
+ /*onlyOwnText*/ true);
+ var outputFiles = [];
+ var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
+ var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle);
+ var emitHost = {
+ getPrependNodes: ts.memoize(function () { return prependNodes.concat([ownPrependInput]); }),
+ getCanonicalFileName: host.getCanonicalFileName,
+ getCommonSourceDirectory: function () { return buildInfo.bundle.commonSourceDirectory; },
+ getCompilerOptions: function () { return config.options; },
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ getNewLine: function () { return host.getNewLine(); },
+ getSourceFile: ts.returnUndefined,
+ getSourceFileByPath: ts.returnUndefined,
+ getSourceFiles: function () { return sourceFilesForJsEmit; },
+ getLibFileFromReference: ts.notImplemented,
+ isSourceFileFromExternalLibrary: ts.returnFalse,
+ getResolvedProjectReferenceToRedirect: ts.returnUndefined,
+ writeFile: function (name, text, writeByteOrderMark) {
+ switch (name) {
+ case jsFilePath:
+ if (jsFileText === text)
+ return;
+ break;
+ case sourceMapFilePath:
+ if (sourceMapText === text)
+ return;
+ break;
+ case buildInfoPath:
+ var newBuildInfo = getBuildInfo(text);
+ newBuildInfo.program = buildInfo.program;
+ // Update sourceFileInfo
+ var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
+ newBuildInfo.bundle.js.sources = js.sources;
+ if (dts) {
+ newBuildInfo.bundle.dts.sources = dts.sources;
+ }
+ newBuildInfo.bundle.sourceFiles = sourceFiles;
+ outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
+ return;
+ case declarationFilePath:
+ if (declarationText === text)
+ return;
+ break;
+ case declarationMapPath:
+ if (declarationMapText === text)
+ return;
+ break;
+ default:
+ ts.Debug.fail("Unexpected path: " + name);
+ }
+ outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
+ },
+ isEmitBlocked: ts.returnFalse,
+ readFile: function (f) { return host.readFile(f); },
+ fileExists: function (f) { return host.fileExists(f); },
+ directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }),
+ useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
+ getProgramBuildInfo: ts.returnUndefined
+ };
+ emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, /*emitOnlyDtsFiles*/ false, ts.getTransformers(config.options));
+ return outputFiles;
+ }
+ ts.emitUsingBuildInfo = emitUsingBuildInfo;
var PipelinePhase;
(function (PipelinePhase) {
PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
@@ -82256,6 +83548,10 @@
var ownWriter; // Reusable `EmitTextWriter` for basic printing.
var write = writeBase;
var isOwnFileEmit;
+ var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
+ var recordInternalSection = printerOptions.recordInternalSection;
+ var sourceFileTextPos = 0;
+ var sourceFileTextKind = "text" /* Text */;
// Source Maps
var sourceMapsDisabled = true;
var sourceMapGenerator;
@@ -82281,7 +83577,8 @@
writeNode: writeNode,
writeList: writeList,
writeFile: writeFile,
- writeBundle: writeBundle
+ writeBundle: writeBundle,
+ bundleFileInfo: bundleFileInfo
};
function printNode(hint, node, sourceFile) {
switch (hint) {
@@ -82296,9 +83593,9 @@
break;
}
switch (node.kind) {
- case 279 /* SourceFile */: return printFile(node);
- case 280 /* Bundle */: return printBundle(node);
- case 281 /* UnparsedSource */: return printUnparsedSource(node);
+ case 284 /* SourceFile */: return printFile(node);
+ case 285 /* Bundle */: return printBundle(node);
+ case 286 /* UnparsedSource */: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -82308,7 +83605,7 @@
return endPrint();
}
function printBundle(bundle) {
- writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined);
+ writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
return endPrint();
}
function printFile(sourceFile) {
@@ -82336,7 +83633,49 @@
reset();
writer = previousWriter;
}
- function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) {
+ function getTextPosWithWriteLine() {
+ return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
+ }
+ function updateOrPushBundleFileTextLike(pos, end, kind) {
+ var last = ts.lastOrUndefined(bundleFileInfo.sections);
+ if (last && last.kind === kind) {
+ last.end = end;
+ }
+ else {
+ bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
+ }
+ }
+ function recordBundleFileInternalSectionStart(node) {
+ if (recordInternalSection &&
+ bundleFileInfo &&
+ currentSourceFile &&
+ (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
+ ts.isInternalDeclaration(node, currentSourceFile) &&
+ sourceFileTextKind !== "internal" /* Internal */) {
+ var prevSourceFileTextKind = sourceFileTextKind;
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = "internal" /* Internal */;
+ return prevSourceFileTextKind;
+ }
+ return undefined;
+ }
+ function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
+ if (prevSourceFileTextKind) {
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = prevSourceFileTextKind;
+ }
+ }
+ function recordBundleFileTextLikeSection(end) {
+ if (sourceFileTextPos < end) {
+ updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
+ return true;
+ }
+ return false;
+ }
+ function writeBundle(bundle, output, sourceMapGenerator) {
+ var _a;
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output, sourceMapGenerator);
@@ -82344,18 +83683,49 @@
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
- var prepend = _b[_a];
+ for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
+ var prepend = _c[_b];
writeLine();
+ var pos = writer.getTextPos();
+ var savedSections = bundleFileInfo && bundleFileInfo.sections;
+ if (savedSections)
+ bundleFileInfo.sections = [];
print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
+ if (bundleFileInfo) {
+ var newSections = bundleFileInfo.sections;
+ bundleFileInfo.sections = savedSections;
+ if (prepend.oldFileOfCurrentEmit)
+ (_a = bundleFileInfo.sections).push.apply(_a, newSections);
+ else {
+ newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prepend" /* Prepend */, data: prepend.fileName, texts: newSections });
}
- if (bundleInfo) {
- bundleInfo.originalOffset = writer.getTextPos();
}
- for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
- var sourceFile = _d[_c];
+ }
+ sourceFileTextPos = getTextPosWithWriteLine();
+ for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
+ var sourceFile = _e[_d];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
+ if (bundleFileInfo && bundle.sourceFiles.length) {
+ var end = writer.getTextPos();
+ if (recordBundleFileTextLikeSection(end)) {
+ // Store prologues
+ var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
+ if (prologues) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.prologues = prologues;
+ }
+ // Store helpes
+ var helpers = getHelpersFromBundledSourceFiles(bundle);
+ if (helpers) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.helpers = helpers;
+ }
+ }
+ }
reset();
writer = previousWriter;
}
@@ -82425,8 +83795,10 @@
function emit(node) {
if (node === undefined)
return;
+ var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
pipelinePhase(4 /* Unspecified */, node);
+ recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
}
function emitIdentifierName(node) {
if (node === undefined)
@@ -82453,12 +83825,12 @@
}
// falls through
case 2 /* Comments */:
- if (!commentsDisabled && node.kind !== 279 /* SourceFile */) {
+ if (!commentsDisabled && node.kind !== 284 /* SourceFile */) {
return pipelineEmitWithComments;
}
// falls through
case 3 /* SourceMaps */:
- if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) {
+ if (!sourceMapsDisabled && node.kind !== 284 /* SourceFile */ && !ts.isInJsonFile(node)) {
return pipelineEmitWithSourceMap;
}
// falls through
@@ -82495,8 +83867,16 @@
case 16 /* TemplateMiddle */:
case 17 /* TemplateTail */:
return emitLiteral(node);
- case 281 /* UnparsedSource */:
- return emitUnparsedSource(node);
+ case 286 /* UnparsedSource */:
+ case 280 /* UnparsedPrepend */:
+ return emitUnparsedSourceOrPrepend(node);
+ case 279 /* UnparsedPrologue */:
+ return writeUnparsedNode(node);
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return emitUnparsedTextLike(node);
+ case 283 /* UnparsedSyntheticReference */:
+ return emitUnparsedSyntheticReference(node);
// Identifiers
case 72 /* Identifier */:
return emitIdentifier(node);
@@ -82540,7 +83920,7 @@
return emitTypeReference(node);
case 165 /* FunctionType */:
return emitFunctionType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return emitJSDocFunctionType(node);
case 166 /* ConstructorType */:
return emitConstructorType(node);
@@ -82578,20 +83958,20 @@
return emitLiteralType(node);
case 183 /* ImportType */:
return emitImportTypeNode(node);
- case 284 /* JSDocAllType */:
+ case 289 /* JSDocAllType */:
writePunctuation("*");
return;
- case 285 /* JSDocUnknownType */:
+ case 290 /* JSDocUnknownType */:
writePunctuation("?");
return;
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return emitJSDocNullableType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return emitJSDocNonNullableType(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return emitJSDocOptionalType(node);
case 172 /* RestType */:
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return emitRestOrJSDocVariadicType(node);
// Binding patterns
case 184 /* ObjectBindingPattern */:
@@ -82729,30 +84109,30 @@
case 278 /* EnumMember */:
return emitEnumMember(node);
// JSDoc nodes (only used in codefixes currently)
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return emitJSDocPropertyLikeTag(node);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return emitJSDocSimpleTypedTag(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return emitJSDocAugmentsTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return emitJSDocTemplateTag(node);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return emitJSDocTypedefTag(node);
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return emitJSDocCallbackTag(node);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return emitJSDocSignature(node);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return emitJSDocTypeLiteral(node);
- case 296 /* JSDocClassTag */:
- case 294 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
return emitJSDocSimpleTag(node);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return emitJSDoc(node);
// Transformation nodes (ignored)
}
@@ -82851,9 +84231,9 @@
case 264 /* JsxFragment */:
return emitJsxFragment(node);
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return emitPartiallyEmittedExpression(node);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return emitCommaList(node);
}
}
@@ -82869,22 +84249,45 @@
var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node);
pipelinePhase(hint, substituteNode(hint, node));
}
+ function getHelpersFromBundledSourceFiles(bundle) {
+ var result;
+ if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
+ return undefined;
+ }
+ var bundledHelpers = ts.createMap();
+ for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
+ var helpers = getSortedEmitHelpers(sourceFile);
+ if (!helpers)
+ continue;
+ for (var _c = 0, helpers_3 = helpers; _c < helpers_3.length; _c++) {
+ var helper = helpers_3[_c];
+ if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
+ bundledHelpers.set(helper.name, true);
+ (result || (result = [])).push(helper.name);
+ }
+ }
+ }
+ return result;
+ }
function emitHelpers(node) {
var helpersEmitted = false;
- var bundle = node.kind === 280 /* Bundle */ ? node : undefined;
+ var bundle = node.kind === 285 /* Bundle */ ? node : undefined;
if (bundle && moduleKind === ts.ModuleKind.None) {
return;
}
- var numNodes = bundle ? bundle.sourceFiles.length : 1;
+ var numPrepends = bundle ? bundle.prepends.length : 0;
+ var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
for (var i = 0; i < numNodes; i++) {
- var currentNode = bundle ? bundle.sourceFiles[i] : node;
- var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile;
- var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined;
- var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit;
- var helpers = ts.getEmitHelpers(currentNode);
+ var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
+ var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
+ var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
+ var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
+ var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
if (helpers) {
- for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
- var helper = _b[_a];
+ for (var _a = 0, helpers_4 = helpers; _a < helpers_4.length; _a++) {
+ var helper = helpers_4[_a];
if (!helper.scoped) {
// Skip the helper if it can be skipped and the noEmitHelpers compiler
// option is set, or if it can be imported and the importHelpers compiler
@@ -82904,18 +84307,25 @@
// Skip the helper if it is scoped and we are emitting bundled helpers
continue;
}
+ var pos = getTextPosWithWriteLine();
if (typeof helper.text === "string") {
writeLines(helper.text);
}
else {
writeLines(helper.text(makeFileLevelOptimisticUniqueName));
}
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
helpersEmitted = true;
}
}
}
return helpersEmitted;
}
+ function getSortedEmitHelpers(node) {
+ var helpers = ts.getEmitHelpers(node);
+ return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
+ }
//
// Literals/Pseudo-literals
//
@@ -82942,8 +84352,42 @@
}
}
// SyntaxKind.UnparsedSource
- function emitUnparsedSource(unparsed) {
- writer.rawWrite(unparsed.text);
+ // SyntaxKind.UnparsedPrepend
+ function emitUnparsedSourceOrPrepend(unparsed) {
+ for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
+ var text = _b[_a];
+ writeLine();
+ emit(text);
+ }
+ }
+ // SyntaxKind.UnparsedPrologue
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ // SyntaxKind.UnparsedSyntheticReference
+ function writeUnparsedNode(unparsed) {
+ writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
+ }
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ function emitUnparsedTextLike(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 281 /* UnparsedText */ ?
+ "text" /* Text */ :
+ "internal" /* Internal */);
+ }
+ }
+ // SyntaxKind.UnparsedSyntheticReference
+ function emitUnparsedSyntheticReference(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ var section = ts.clone(unparsed.section);
+ section.pos = pos;
+ section.end = writer.getTextPos();
+ bundleFileInfo.sections.push(section);
+ }
}
//
// Identifiers
@@ -82998,7 +84442,7 @@
emit(node.dotDotDotToken);
emitNodeWithWriter(node.name, writeParameter);
emit(node.questionToken);
- if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) {
+ if (node.parent && node.parent.kind === 294 /* JSDocFunctionType */ && !node.name) {
emit(node.type);
}
else {
@@ -83878,7 +85322,7 @@
}
function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
// Emit all the prologue directives (like "use strict").
- var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true);
+ var statementOffset = emitPrologueDirectives(body.statements);
var pos = writer.getTextPos();
emitHelpers(body);
if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
@@ -84138,7 +85582,7 @@
writePunctuation(">");
}
function emitJsxText(node) {
- writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true));
+ writer.writeLiteral(node.text);
}
function emitJsxClosingElementOrFragment(node) {
writePunctuation("</");
@@ -84283,7 +85727,7 @@
}
}
if (node.tags) {
- if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) {
+ if (node.tags.length === 1 && node.tags[0].kind === 307 /* JSDocTypeTag */ && !node.comment) {
writeSpace();
emit(node.tags[0]);
}
@@ -84317,7 +85761,7 @@
function emitJSDocTypedefTag(tag) {
emitJSDocTagName(tag.tagName);
if (tag.typeExpression) {
- if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
emitJSDocTypeExpression(tag.typeExpression);
}
else {
@@ -84336,7 +85780,7 @@
emit(tag.fullName);
}
emitJSDocComment(tag.comment);
- if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) {
+ if (tag.typeExpression && tag.typeExpression.kind === 297 /* JSDocTypeLiteral */) {
emitJSDocTypeLiteral(tag.typeExpression);
}
}
@@ -84423,6 +85867,16 @@
}
function emitSyntheticTripleSlashReferencesIfNeeded(node) {
emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
+ for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
+ for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
+ var ref = _d[_c];
+ emit(ref);
+ writeLine();
+ }
+ }
+ }
}
function emitTripleSlashDirectivesIfNeeded(node) {
if (node.isDeclarationFile)
@@ -84430,7 +85884,10 @@
}
function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
if (hasNoDefaultLib) {
+ var pos = writer.getTextPos();
writeComment("/// <reference no-default-lib=\"true\"/>");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
writeLine();
}
if (currentSourceFile && currentSourceFile.moduleName) {
@@ -84451,17 +85908,26 @@
}
for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
var directive = files_1[_c];
+ var pos = writer.getTextPos();
writeComment("/// <reference path=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
writeLine();
}
- for (var _d = 0, types_18 = types; _d < types_18.length; _d++) {
- var directive = types_18[_d];
+ for (var _d = 0, types_19 = types; _d < types_19.length; _d++) {
+ var directive = types_19[_d];
+ var pos = writer.getTextPos();
writeComment("/// <reference types=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
writeLine();
}
for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
var directive = libs_1[_e];
+ var pos = writer.getTextPos();
writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
writeLine();
}
}
@@ -84486,16 +85952,22 @@
* Emits any prologue directives at the start of a Statement list, returning the
* number of prologue directives written to the output.
*/
- function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) {
+ function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
+ var needsToSetSourceFile = !!sourceFile;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (ts.isPrologueDirective(statement)) {
var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
if (shouldEmitPrologueDirective) {
- if (startWithNewLine || i > 0) {
- writeLine();
+ if (needsToSetSourceFile) {
+ needsToSetSourceFile = false;
+ setSourceFile(sourceFile);
}
+ writeLine();
+ var pos = writer.getTextPos();
emit(statement);
+ if (recordBundleFileSection && bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
if (seenPrologueDirectives) {
seenPrologueDirectives.set(statement.expression.text, true);
}
@@ -84508,23 +85980,70 @@
}
return statements.length;
}
+ function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
+ for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
+ var prologue = prologues_1[_a];
+ if (!seenPrologueDirectives.has(prologue.data)) {
+ writeLine();
+ var pos = writer.getTextPos();
+ emit(prologue);
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
+ if (seenPrologueDirectives) {
+ seenPrologueDirectives.set(prologue.data, true);
+ }
+ }
+ }
+ }
function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
if (ts.isSourceFile(sourceFileOrBundle)) {
- setSourceFile(sourceFileOrBundle);
- emitPrologueDirectives(sourceFileOrBundle.statements);
+ emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
}
else {
var seenPrologueDirectives = ts.createMap();
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
- setSourceFile(sourceFile);
- emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
+ emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
}
setSourceFile(undefined);
}
}
+ function getPrologueDirectivesFromBundledSourceFiles(bundle) {
+ var seenPrologueDirectives = ts.createMap();
+ var prologues;
+ for (var index = 0; index < bundle.sourceFiles.length; index++) {
+ var sourceFile = bundle.sourceFiles[index];
+ var directives = void 0;
+ var end = 0;
+ for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
+ var statement = _b[_a];
+ if (!ts.isPrologueDirective(statement))
+ break;
+ if (seenPrologueDirectives.has(statement.expression.text))
+ continue;
+ seenPrologueDirectives.set(statement.expression.text, true);
+ (directives || (directives = [])).push({
+ pos: statement.pos,
+ end: statement.end,
+ expression: {
+ pos: statement.expression.pos,
+ end: statement.expression.end,
+ text: statement.expression.text
+ }
+ });
+ end = end < statement.end ? statement.end : end;
+ }
+ if (directives)
+ (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
+ }
+ return prologues;
+ }
function emitShebangIfNeeded(sourceFileOrBundle) {
- if (ts.isSourceFile(sourceFileOrBundle)) {
+ if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
var shebang = ts.getShebang(sourceFileOrBundle.text);
if (shebang) {
writeComment(shebang);
@@ -84533,11 +86052,18 @@
}
}
else {
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ ts.Debug.assertNode(prepend, ts.isUnparsedSource);
+ if (emitShebangIfNeeded(prepend)) {
+ return true;
+ }
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
// Emit only the first encountered shebang
if (emitShebangIfNeeded(sourceFile)) {
- break;
+ return true;
}
}
}
@@ -84740,6 +86266,7 @@
}
// Emit each child.
var previousSibling = void 0;
+ var previousSourceFileTextKind = void 0;
var shouldDecreaseIndentAfterEmit = false;
for (var i = 0; i < count; i++) {
var child = children[start + i];
@@ -84760,6 +86287,7 @@
emitLeadingCommentsOfPosition(previousSibling.end);
}
writeDelimiter(format);
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write either a line terminator or whitespace to separate the elements.
if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
// If a synthesized node in a single-line list starts on a new
@@ -84776,6 +86304,7 @@
}
}
// Emit this child.
+ previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
if (shouldEmitInterveningComments) {
if (emitTrailingCommentsOfPosition) {
var commentRange = ts.getCommentRange(child);
@@ -84810,6 +86339,7 @@
if (format & 128 /* Indented */) {
decreaseIndent();
}
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write the closing line terminator or closing whitespace.
if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
writeLine();
@@ -84911,7 +86441,6 @@
if (line.length) {
writeLine();
write(line);
- writer.rawWrite(newLine);
}
}
}
@@ -85425,7 +86954,7 @@
hasWrittenComment = false;
var emitFlags = ts.getEmitFlags(node);
var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
- var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 312 /* 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 === 11 /* JsxText */;
@@ -85685,19 +87214,28 @@
return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
}
// Source Maps
+ function getParsedSourceMap(node) {
+ if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
+ node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
+ }
+ return node.parsedSourceMap || undefined;
+ }
function pipelineEmitWithSourceMap(hint, node) {
var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node);
- if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) {
- var parsed = ts.tryParseRawSourceMap(node.sourceMapText);
- if (parsed) {
- sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath);
+ if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
+ pipelinePhase(hint, node);
+ }
+ else if (ts.isUnparsedNode(node)) {
+ var parsed = getParsedSourceMap(node.parent);
+ if (parsed && sourceMapGenerator) {
+ sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
}
pipelinePhase(hint, node);
}
else {
var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
var emitFlags = ts.getEmitFlags(node);
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitSourcePos(source, skipSourceTrivia(source, pos));
@@ -85710,7 +87248,7 @@
else {
pipelinePhase(hint, node);
}
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitSourcePos(source, end);
@@ -85838,7 +87376,8 @@
writeFile: host.writeFile && writeFile,
addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
addOrDeleteFile: addOrDeleteFile,
- clearCache: clearCache
+ clearCache: clearCache,
+ realpath: host.realpath && realpath
};
function toPath(fileName) {
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
@@ -85935,7 +87474,7 @@
var rootDirPath = toPath(rootDir);
var result = tryReadDirectory(rootDir, rootDirPath);
if (result) {
- return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries);
+ return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
}
return host.readDirectory(rootDir, extensions, excludes, includes, depth);
function getFileSystemEntries(dir) {
@@ -85946,6 +87485,9 @@
return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
}
}
+ function realpath(s) {
+ return host.realpath ? host.realpath(s) : s;
+ }
function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
if (existingResult) {
@@ -86216,11 +87758,7 @@
function createCompilerHostWorker(options, setParentNodes, system) {
if (system === void 0) { system = ts.sys; }
var existingDirectories = ts.createMap();
- function getCanonicalFileName(fileName) {
- // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
- // otherwise use toLowerCase as a canonical form.
- return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
- }
+ var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
function getSourceFile(fileName, languageVersion, onError) {
var text;
try {
@@ -86345,20 +87883,21 @@
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
- return value || undefined;
+ return value !== false ? value : undefined;
return setReadFileCache(key, fileName);
};
var setReadFileCache = function (key, fileName) {
var newValue = originalReadFile.call(host, fileName);
- readFileCache.set(key, newValue || false);
+ readFileCache.set(key, newValue !== undefined ? newValue : false);
return newValue;
};
host.readFile = function (fileName) {
var key = toPath(fileName);
var value = readFileCache.get(key);
if (value !== undefined)
- return value; // could be .d.ts from output
- if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ return value !== false ? value : undefined; // could be .d.ts from output
+ // Cache json or buildInfo
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
return originalReadFile.call(host, fileName);
}
return setReadFileCache(key, fileName);
@@ -86389,7 +87928,7 @@
var key = toPath(fileName);
fileExistsCache.delete(key);
var value = readFileCache.get(key);
- if (value && value !== data) {
+ if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.delete(key);
}
@@ -86835,11 +88374,18 @@
if (rootNames.length) {
for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
var parsedRef = resolvedProjectReferences_1[_i];
- if (parsedRef) {
+ if (!parsedRef)
+ continue;
var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
if (out) {
- var dtsOutfile = ts.changeExtension(out, ".d.ts");
- processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ }
+ else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
+ for (var _a = 0, _b = parsedRef.commandLine.fileNames; _a < _b.length; _a++) {
+ var fileName = _b[_a];
+ if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(fileName)) {
+ processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
+ }
}
}
}
@@ -86887,8 +88433,8 @@
// not part of the new program.
if (oldProgram && host.onReleaseOldSourceFile) {
var oldSourceFiles = oldProgram.getSourceFiles();
- for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) {
- var oldSourceFile = oldSourceFiles_1[_a];
+ for (var _c = 0, oldSourceFiles_1 = oldSourceFiles; _c < oldSourceFiles_1.length; _c++) {
+ var oldSourceFile = oldSourceFiles_1[_c];
var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
if (shouldCreateNewSourceFile || !newFile ||
// old file wasnt redirect but new file is
@@ -86944,7 +88490,8 @@
getProjectReferenceRedirect: getProjectReferenceRedirect,
getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
- forEachResolvedProjectReference: forEachResolvedProjectReference
+ forEachResolvedProjectReference: forEachResolvedProjectReference,
+ emitBuildInfo: emitBuildInfo
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -86973,7 +88520,7 @@
}
function getCommonSourceDirectory() {
if (commonSourceDirectory === undefined) {
- var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); });
+ var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); });
if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
// If a rootDir is specified use it as the commonSourceDirectory
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
@@ -87362,7 +88909,8 @@
}
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, getLibFileFromReference: program.getLibFileFromReference, 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) {
+ 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, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
+ getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, 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))
@@ -87371,7 +88919,20 @@
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(); } });
+ } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); } });
+ }
+ function emitBuildInfo(writeFileCallback) {
+ ts.Debug.assert(!options.out && !options.outFile);
+ ts.performance.mark("beforeEmit");
+ var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback),
+ /*targetSourceFile*/ undefined,
+ /*emitOnlyDtsFiles*/ false,
+ /*transformers*/ undefined,
+ /*declaraitonTransformers*/ undefined,
+ /*onlyBuildInfo*/ true);
+ ts.performance.mark("afterEmit");
+ ts.performance.measure("Emit", "beforeEmit", "afterEmit");
+ return emitResult;
}
function getResolvedProjectReferences() {
return resolvedProjectReferences;
@@ -87380,28 +88941,11 @@
return projectReferences;
}
function getPrependNodes() {
- if (!projectReferences) {
- return ts.emptyArray;
- }
- var nodes = [];
- for (var i = 0; i < projectReferences.length; i++) {
- var ref = projectReferences[i];
- var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
- if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
- var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
- // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
- if (!out)
- continue;
- var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- var node = ts.createInputFiles(function (fileName) {
+ return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
var path = toPath(fileName);
var sourceFile = getSourceFileByPath(path);
return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
- }, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath);
- nodes.push(node);
- }
- }
- return nodes;
+ });
}
function isSourceFileFromExternalLibrary(file) {
return !!sourceFilesFoundSearchingNodeModules.get(file.path);
@@ -87473,8 +89017,7 @@
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
ts.performance.mark("beforeEmit");
var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217
- emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -88086,7 +89629,6 @@
if (refFile) {
var redirect = getProjectReferenceRedirect(fileName);
if (redirect) {
- (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName);
fileName = redirect;
// Once we start redirecting to a file, we can potentially come back to it
// via a back-reference from another file in the .d.ts folder. If that happens we'll
@@ -88183,7 +89725,7 @@
var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
return out ?
ts.changeExtension(out, ".d.ts" /* Dts */) :
- ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine);
+ ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
}
/**
* Get the referenced project if the file is input file from that reference project
@@ -88476,18 +90018,29 @@
if (options.declaration === false) {
createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
}
+ if (options.incremental === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
+ }
+ }
+ if (options.tsBuildInfoFile) {
+ if (!ts.isIncrementalCompilation(options)) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
+ }
}
verifyProjectReferences();
// List of collected files is complete; validate exhautiveness if this is a project with a file list
if (options.composite) {
- var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; });
- if (rootNames.length < sourceFiles.length) {
- var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); });
- for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) {
- var file = _a[_i];
- if (normalizedRootNames.indexOf(file) === -1) {
- 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));
- }
+ var rootPaths = rootNames.map(toPath);
+ for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
+ var file = files_3[_i];
+ // Ignore declaration files
+ if (file.isDeclarationFile)
+ continue;
+ // Ignore json file thats from project reference
+ if (ts.isJsonSourceFile(file) && getResolvedProjectReferenceToRedirect(file.fileName))
+ continue;
+ if (rootPaths.indexOf(file.path) === -1) {
+ 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.fileName));
}
}
}
@@ -88670,6 +90223,7 @@
}
}
function verifyProjectReferences() {
+ var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getOutputPathForBuildInfo(options) : undefined;
forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
var parentFile = parent && parent.sourceFile;
@@ -88696,6 +90250,10 @@
createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
}
}
+ if (!parent && buildInfoPath && buildInfoPath === ts.getOutputPathForBuildInfo(options)) {
+ createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
+ hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
+ }
});
}
function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
@@ -88840,11 +90398,32 @@
readFile: function (f) { return directoryStructureHost.readFile(f); },
useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
getCurrentDirectory: function () { return host.getCurrentDirectory(); },
- onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || (function () { return undefined; }),
+ onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
trace: host.trace ? function (s) { return host.trace(s); } : undefined
};
}
ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
+ /* @internal */
+ function createPrependNodes(projectReferences, getCommandLine, readFile) {
+ if (!projectReferences)
+ return ts.emptyArray;
+ var nodes;
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = getCommandLine(ref, i);
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!out)
+ continue;
+ var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
+ (nodes || (nodes = [])).push(node);
+ }
+ }
+ return nodes || ts.emptyArray;
+ }
+ ts.createPrependNodes = createPrependNodes;
function resolveProjectReferencePath(hostOrRef, ref) {
var passedInRef = ref ? ref : hostOrRef;
return ts.resolveConfigFileProjectName(passedInRef.path);
@@ -89041,7 +90620,7 @@
// Create the reference map, and set the file infos
for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
- var version_1 = sourceFile.version;
+ var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined;
if (referencedMap) {
var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
@@ -89096,9 +90675,9 @@
*/
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
+ // They will be committed once it is safe to use them
// eg when calling this api from tsserver, if there is no cancellation of the operation
- // In the other cases the affected files signatures are commited only after the iteration through the result is complete
+ // In the other cases the affected files signatures are committed only after the iteration through the result is complete
var signatureCache = cacheToUpdateSignature || ts.createMap();
var sourceFile = programOfThisState.getSourceFileByPath(path);
if (!sourceFile) {
@@ -89388,11 +90967,14 @@
var affectedSignatures = oldState.currentAffectedFilesSignatures;
ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
}
+ var changedFilesSet = oldState.changedFilesSet;
if (canCopySemanticDiagnostics) {
- ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
+ ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
}
// Copy old state's changed files set
- ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet);
+ if (changedFilesSet) {
+ ts.copyEntries(changedFilesSet, state.changedFilesSet);
+ }
if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit;
state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
@@ -89430,7 +91012,7 @@
// Unchanged file copy diagnostics
var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
if (diagnostics) {
- state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics);
+ state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics);
if (!state.semanticDiagnosticsFromOldState) {
state.semanticDiagnosticsFromOldState = ts.createMap();
}
@@ -89438,8 +91020,45 @@
}
}
});
+ if (oldCompilerOptions &&
+ (oldCompilerOptions.outDir !== compilerOptions.outDir ||
+ oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
+ (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
+ // Add all files to affectedFilesPendingEmit since emit changed
+ state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(function (f) { return f.path; }));
+ if (state.affectedFilesPendingEmitIndex === undefined) {
+ state.affectedFilesPendingEmitIndex = 0;
+ }
+ ts.Debug.assert(state.seenAffectedFiles === undefined);
+ state.seenAffectedFiles = ts.createMap();
+ }
return state;
}
+ function convertToDiagnostics(diagnostics, newProgram) {
+ if (!diagnostics.length)
+ return ts.emptyArray;
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToDiagnosticRelatedInformation(diagnostic, newProgram) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && newProgram.getSourceFileByPath(file), messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToDiagnosticMessageChain(messageText, newProgram) });
+ }
+ function convertToDiagnosticMessageChain(diagnostic, newProgram) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram) });
+ }
/**
* Releases program and other related not needed properties
*/
@@ -89659,8 +91278,11 @@
* 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
*/
- function doneWithAffectedFile(state, affected, isPendingEmit) {
- if (affected === state.program) {
+ function doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit) {
+ if (isBuildInfoEmit) {
+ state.emittedBuildInfo = true;
+ }
+ else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
@@ -89677,8 +91299,8 @@
/**
* Returns the result with affected file
*/
- function toAffectedFileResult(state, result, affected, isPendingEmit) {
- doneWithAffectedFile(state, affected, isPendingEmit);
+ function toAffectedFileResult(state, result, affected, isPendingEmit, isBuildInfoEmit) {
+ doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
return { result: result, affected: affected };
}
/**
@@ -89701,6 +91323,77 @@
}
return diagnostics;
}
+ /**
+ * Gets the program information to be emitted in buildInfo so that we can use it to create new program
+ */
+ function getProgramBuildInfo(state) {
+ if (state.compilerOptions.outFile || state.compilerOptions.out)
+ return undefined;
+ var fileInfos = {};
+ state.fileInfos.forEach(function (value, key) {
+ var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
+ fileInfos[key] = signature === undefined ? value : { version: value.version, signature: signature };
+ });
+ var result = { fileInfos: fileInfos, options: state.compilerOptions };
+ if (state.referencedMap) {
+ var referencedMap_1 = {};
+ state.referencedMap.forEach(function (value, key) {
+ referencedMap_1[key] = ts.arrayFrom(value.keys());
+ });
+ result.referencedMap = referencedMap_1;
+ }
+ if (state.exportedModulesMap) {
+ var exportedModulesMap_1 = {};
+ state.exportedModulesMap.forEach(function (value, key) {
+ var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
+ // Not in temporary cache, use existing value
+ if (newValue === undefined)
+ exportedModulesMap_1[key] = ts.arrayFrom(value.keys());
+ // Value in cache and has updated value map, use that
+ else if (newValue)
+ exportedModulesMap_1[key] = ts.arrayFrom(newValue.keys());
+ });
+ result.exportedModulesMap = exportedModulesMap_1;
+ }
+ if (state.semanticDiagnosticsPerFile) {
+ var semanticDiagnosticsPerFile_1 = [];
+ // Currently not recording actual errors since those mean no emit for tsc --build
+ state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ?
+ [
+ key,
+ state.hasReusableDiagnostic ?
+ value :
+ convertToReusableDiagnostics(value)
+ ] :
+ key); });
+ result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1;
+ }
+ return result;
+ }
+ function convertToReusableDiagnostics(diagnostics) {
+ ts.Debug.assert(!!diagnostics.length);
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToReusableDiagnosticRelatedInformation(diagnostic);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToReusableDiagnosticRelatedInformation(diagnostic) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && file.path, messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToReusableDiagnosticMessageChain(messageText) });
+ }
+ function convertToReusableDiagnosticMessageChain(diagnostic) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next) });
+ }
var BuilderProgramKind;
(function (BuilderProgramKind) {
BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
@@ -89757,6 +91450,7 @@
var computeHash = host.createHash || ts.generateDjb2Hash;
var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
var backupState;
+ newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state); };
// To ensure that we arent storing any references to old program or new program without state
newProgram = undefined; // TODO: GH#18217
oldProgram = undefined;
@@ -89800,8 +91494,17 @@
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
affected = getNextAffectedFilePendingEmit(state);
if (!affected) {
+ if (state.emittedBuildInfo) {
return undefined;
}
+ var affected_1 = ts.Debug.assertDefined(state.program);
+ return toAffectedFileResult(state,
+ // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
+ // Otherwise just affected file
+ affected_1.emitBuildInfo(writeFile || host.writeFile, cancellationToken), affected_1,
+ /*isPendingEmitFile*/ false,
+ /*isBuildInfoEmit*/ true);
+ }
isPendingEmitFile = true;
}
else {
@@ -89926,13 +91629,60 @@
}
var diagnostics;
for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
- var sourceFile_2 = _a[_i];
- diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken));
+ var sourceFile_1 = _a[_i];
+ diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
}
return diagnostics || ts.emptyArray;
}
}
ts.createBuilderProgram = createBuilderProgram;
+ function getMapOfReferencedSet(mapLike) {
+ if (!mapLike)
+ return undefined;
+ var map = ts.createMap();
+ // Copies keys/values from template. Note that for..in will not throw if
+ // template is undefined, and instead will just exit the loop.
+ for (var key in mapLike) {
+ if (ts.hasProperty(mapLike, key)) {
+ map.set(key, ts.arrayToSet(mapLike[key]));
+ }
+ }
+ return map;
+ }
+ function createBuildProgramUsingProgramBuildInfo(program) {
+ var fileInfos = ts.createMapFromTemplate(program.fileInfos);
+ var state = {
+ fileInfos: fileInfos,
+ compilerOptions: program.options,
+ referencedMap: getMapOfReferencedSet(program.referencedMap),
+ exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
+ semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return ts.isString(value) ? value : value[0]; }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
+ hasReusableDiagnostic: true
+ };
+ return {
+ getState: function () { return state; },
+ backupState: ts.noop,
+ restoreState: ts.noop,
+ getProgram: ts.notImplemented,
+ getProgramOrUndefined: ts.returnUndefined,
+ releaseProgram: ts.noop,
+ getCompilerOptions: function () { return state.compilerOptions; },
+ getSourceFile: ts.notImplemented,
+ getSourceFiles: ts.notImplemented,
+ getOptionsDiagnostics: ts.notImplemented,
+ getGlobalDiagnostics: ts.notImplemented,
+ getConfigFileParsingDiagnostics: ts.notImplemented,
+ getSyntacticDiagnostics: ts.notImplemented,
+ getDeclarationDiagnostics: ts.notImplemented,
+ getSemanticDiagnostics: ts.notImplemented,
+ emit: ts.notImplemented,
+ getAllDependencies: ts.notImplemented,
+ getCurrentDirectory: ts.notImplemented,
+ emitNextAffectedFile: ts.notImplemented,
+ getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
+ };
+ }
+ ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
return {
getState: ts.notImplemented,
@@ -89952,7 +91702,7 @@
getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
getAllDependencies: ts.notImplemented,
- getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); }
+ getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
};
function getProgram() {
return ts.Debug.assertDefined(state.program);
@@ -89978,10 +91728,10 @@
/*@internal*/
var ts;
(function (ts) {
- function isPathInNodeModulesStartingWithDot(path) {
- return ts.stringContains(path, "/node_modules/.");
+ function isPathIgnored(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); });
}
- ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot;
+ ts.isPathIgnored = isPathIgnored;
ts.maxNumberOfFilesToIterateForInvalidation = 256;
function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
var filesWithChangedSetOfUnresolvedImports;
@@ -90503,7 +92253,7 @@
}
else {
// If something to do with folder/file starting with "." in node_modules folder, skip it
- if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (isPathIgnored(fileOrDirectoryPath))
return false;
// Some file or directory in the watching directory is created
// Return early if it does not have any of the watching extension or not the custom failed lookup path
@@ -90980,6 +92730,8 @@
case ".jsx" /* Jsx */:
case ".json" /* Json */:
return ext;
+ case ".tsbuildinfo" /* TsBuildInfo */:
+ return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
default:
return ts.Debug.assertNever(ext);
}
@@ -91100,22 +92852,18 @@
var diagnostics = program.getConfigFileParsingDiagnostics().slice();
var configFileParsingDiagnosticsLength = diagnostics.length;
ts.addRange(diagnostics, program.getSyntacticDiagnostics());
- var reportSemanticDiagnostics = false;
// If we didn't have any syntactic errors, then also try getting the global and
// semantic errors.
if (diagnostics.length === configFileParsingDiagnosticsLength) {
ts.addRange(diagnostics, program.getOptionsDiagnostics());
ts.addRange(diagnostics, program.getGlobalDiagnostics());
if (diagnostics.length === configFileParsingDiagnosticsLength) {
- reportSemanticDiagnostics = true;
+ ts.addRange(diagnostics, program.getSemanticDiagnostics());
}
}
// Emit and report any errors we ran into.
var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics;
ts.addRange(diagnostics, emitDiagnostics);
- if (reportSemanticDiagnostics) {
- ts.addRange(diagnostics, program.getSemanticDiagnostics());
- }
ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic);
if (writeFileName) {
var currentDir_1 = program.getCurrentDirectory();
@@ -91236,6 +92984,22 @@
}
}
ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
+ function setGetSourceFileAsHashVersioned(compilerHost, host) {
+ var originalGetSourceFile = compilerHost.getSourceFile;
+ var computeHash = host.createHash || ts.generateDjb2Hash;
+ compilerHost.getSourceFile = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
+ if (result) {
+ result.version = computeHash.call(host, result.text);
+ }
+ return result;
+ };
+ }
+ ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
/**
* Creates the watch compiler host that can be extended with config file or root file names and options host
*/
@@ -91261,7 +93025,7 @@
writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
createHash: ts.maybeBind(system, system.createHash),
- createProgram: createProgram
+ createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
};
}
ts.createProgramHost = createProgramHost;
@@ -91271,7 +93035,7 @@
function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
var writeFileName = function (s) { return system.write(s + system.newLine); };
- var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram);
+ var result = createProgramHost(system, createProgram);
ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = function (builderProgram) {
var compilerOptions = builderProgram.getCompilerOptions();
@@ -91310,6 +93074,49 @@
return host;
}
ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
+ function readBuilderProgram(compilerOptions, readFile) {
+ if (compilerOptions.out || compilerOptions.outFile)
+ return undefined;
+ var buildInfoPath = ts.getOutputPathForBuildInfo(compilerOptions);
+ if (!buildInfoPath)
+ return undefined;
+ var content = readFile(buildInfoPath);
+ if (!content)
+ return undefined;
+ var buildInfo = ts.getBuildInfo(content);
+ if (buildInfo.version !== ts.version)
+ return undefined;
+ if (!buildInfo.program)
+ return undefined;
+ return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program);
+ }
+ ts.readBuilderProgram = readBuilderProgram;
+ function createIncrementalCompilerHost(options, system) {
+ if (system === void 0) { system = ts.sys; }
+ var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
+ host.createHash = ts.maybeBind(system, system.createHash);
+ setGetSourceFileAsHashVersioned(host, system);
+ ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
+ return host;
+ }
+ ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
+ function createIncrementalProgram(_a) {
+ var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
+ host = host || createIncrementalCompilerHost(options);
+ createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
+ var oldProgram = readBuilderProgram(options, function (path) { return host.readFile(path); });
+ return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
+ }
+ function performIncrementalCompilation(input) {
+ var system = input.system || ts.sys;
+ var host = input.host || (input.host = createIncrementalCompilerHost(input.options, system));
+ var builderProgram = createIncrementalProgram(input);
+ var exitStatus = emitFilesAndReportErrors(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined);
+ if (input.afterProgramEmitAndDiagnostics)
+ input.afterProgramEmitAndDiagnostics(builderProgram);
+ return exitStatus;
+ }
+ ts.performIncrementalCompilation = performIncrementalCompilation;
})(ts || (ts = {}));
(function (ts) {
function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) {
@@ -91321,7 +93128,6 @@
}
}
ts.createWatchCompilerHost = createWatchCompilerHost;
- var initialVersion = 1;
function createWatchProgram(host) {
var builderProgram;
var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
@@ -91362,10 +93168,12 @@
var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
+ var configFileWatcher;
if (configFileName) {
- watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */);
+ configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */);
}
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
+ ts.setGetSourceFileAsHashVersioned(compilerHost, host);
// Members for CompilerHost
var getNewSourceFile = compilerHost.getSourceFile;
compilerHost.getSourceFile = function (fileName) {
@@ -91406,21 +93214,43 @@
(function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) :
(function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
+ builderProgram = ts.readBuilderProgram(compilerOptions, function (path) { return compilerHost.readFile(path); });
synchronizeProgram();
// Update the wild card directory watch
watchConfigFileWildCardDirectories();
return configFileName ?
- { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } :
- { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames };
+ { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } :
+ { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close };
+ function close() {
+ resolutionCache.clear();
+ ts.clearMap(sourceFilesCache, function (value) {
+ if (value && value.fileWatcher) {
+ value.fileWatcher.close();
+ value.fileWatcher = undefined;
+ }
+ });
+ if (configFileWatcher) {
+ configFileWatcher.close();
+ configFileWatcher = undefined;
+ }
+ if (watchedWildcardDirectories) {
+ ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
+ watchedWildcardDirectories = undefined;
+ }
+ if (missingFilesMap) {
+ ts.clearMap(missingFilesMap, ts.closeFileWatcher);
+ missingFilesMap = undefined;
+ }
+ }
function getCurrentBuilderProgram() {
return builderProgram;
}
function getCurrentProgram() {
- return builderProgram && builderProgram.getProgram();
+ return builderProgram && builderProgram.getProgramOrUndefined();
}
function synchronizeProgram() {
writeLog("Synchronizing program");
- var program = getCurrentProgram();
+ var program = getCurrentBuilderProgram();
if (hasChangedCompilerOptions) {
newLine = updateNewLine();
if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
@@ -91436,19 +93266,19 @@
}
}
else {
- createNewProgram(program, hasInvalidatedResolution);
+ createNewProgram(hasInvalidatedResolution);
}
if (host.afterProgramCreate) {
host.afterProgramCreate(builderProgram);
}
return builderProgram;
}
- function createNewProgram(program, hasInvalidatedResolution) {
+ function createNewProgram(hasInvalidatedResolution) {
// Compile the program
writeLog("CreatingProgramWith::");
writeLog(" roots: " + JSON.stringify(rootFileNames));
writeLog(" options: " + JSON.stringify(compilerOptions));
- var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program;
+ var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
hasChangedCompilerOptions = false;
hasChangedConfigFileParsingErrors = false;
resolutionCache.startCachingPerDirectoryResolution();
@@ -91488,10 +93318,10 @@
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
}
function isFileMissingOnHost(hostSourceFile) {
- return typeof hostSourceFile === "number";
+ return typeof hostSourceFile === "boolean";
}
- function isFilePresentOnHost(hostSourceFile) {
- return !!hostSourceFile.sourceFile;
+ function isFilePresenceUnknownOnHost(hostSourceFile) {
+ return typeof hostSourceFile.version === "boolean";
}
function fileExists(fileName) {
var path = toPath(fileName);
@@ -91509,36 +93339,32 @@
return undefined;
}
// Create new source file if requested or the versions dont match
- if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) {
+ if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
if (hostSourceFile) {
- if (shouldCreateNewSourceFile) {
- hostSourceFile.version++;
- }
if (sourceFile) {
// Set the source file and create file watcher now that file was present on the disk
hostSourceFile.sourceFile = sourceFile;
- sourceFile.version = hostSourceFile.version.toString();
+ hostSourceFile.version = sourceFile.version;
if (!hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */);
}
}
else {
// There is no source file on host any more, close the watch, missing file paths will track it
- if (isFilePresentOnHost(hostSourceFile)) {
+ if (hostSourceFile.fileWatcher) {
hostSourceFile.fileWatcher.close();
}
- sourceFilesCache.set(path, hostSourceFile.version);
+ sourceFilesCache.set(path, false);
}
}
else {
if (sourceFile) {
- sourceFile.version = initialVersion.toString();
var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */);
- sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher });
+ sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
}
else {
- sourceFilesCache.set(path, initialVersion);
+ sourceFilesCache.set(path, false);
}
}
return sourceFile;
@@ -91550,16 +93376,16 @@
if (hostSourceFile !== undefined) {
if (isFileMissingOnHost(hostSourceFile)) {
// The next version, lets set it as presence unknown file
- sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 });
+ sourceFilesCache.set(path, { version: false });
}
else {
- hostSourceFile.version++;
+ hostSourceFile.version = false;
}
}
}
function getSourceVersion(path) {
var hostSourceFile = sourceFilesCache.get(path);
- return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString();
+ return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
}
function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
@@ -91567,7 +93393,7 @@
// remove the cached entry.
// Note we arent deleting entry if file became missing in new program or
// there was version update and new source file was created.
- if (hostSourceFileInfo) {
+ if (hostSourceFileInfo !== undefined) {
// record the missing file paths so they can be removed later if watchers arent tracking them
if (isFileMissingOnHost(hostSourceFileInfo)) {
(missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
@@ -91656,7 +93482,7 @@
function onSourceFileChange(fileName, eventKind, path) {
updateCachedSystemWithFile(fileName, path, eventKind);
// Update the source file cache
- if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) {
+ if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
resolutionCache.invalidateResolutionOfFile(path);
}
resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
@@ -91700,7 +93526,7 @@
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
nextSourceFileVersion(fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
// 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
@@ -91754,16 +93580,23 @@
* This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
*/
UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
- UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream";
- UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate";
- UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked";
- UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream";
+ /**
+ * The project appears out of date because its upstream inputs are newer than its outputs,
+ * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
+ * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
+ */
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
+ UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
+ UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
+ UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
+ UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
+ UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
/**
* Projects with no outputs (i.e. "solution" files)
*/
- UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly";
+ UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
})(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
function createFileMap(toPath) {
// tslint:disable-next-line:no-null-keyword
@@ -91811,61 +93644,6 @@
function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
}
- 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);
- return ts.changeExtension(outputPath, ".d.ts" /* Dts */);
- }
- ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
- function getOutputJSFileName(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);
- 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) {
- // 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 = [];
- var js = getOutputJSFileName(inputFileName, configFile);
- outputs.push(js);
- if (configFile.options.sourceMap) {
- outputs.push(js + ".map");
- }
- 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");
- }
- }
- return outputs;
- }
- function getOutFileOutputs(project) {
- var out = project.options.outFile || project.options.out;
- if (!out) {
- return ts.Debug.fail("outFile must be set");
- }
- var outputs = [];
- outputs.push(out);
- if (project.options.sourceMap) {
- outputs.push(out + ".map");
- }
- if (ts.getEmitDeclarations(project.options)) {
- var dts = ts.changeExtension(out, ".d.ts" /* Dts */);
- outputs.push(dts);
- if (project.options.declarationMap) {
- outputs.push(dts + ".map");
- }
- }
- return outputs;
- }
- function rootDirOfOptions(opts, configFileName) {
- return opts.rootDir || ts.getDirectoryPath(configFileName);
- }
function newer(date1, date2) {
return date2 > date1 ? date2 : date1;
}
@@ -91885,7 +93663,7 @@
ts.createBuilderStatusReporter = createBuilderStatusReporter;
function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
var host = ts.createProgramHost(system, createProgram);
- host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; };
+ host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
@@ -91894,14 +93672,14 @@
}
function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
host.reportErrorSummary = reportErrorSummary;
return host;
}
ts.createSolutionBuilderHost = createSolutionBuilderHost;
function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
var watchHost = ts.createWatchHost(system, reportWatchStatus);
ts.copyProperties(host, watchHost);
return host;
@@ -91933,9 +93711,8 @@
var readFileWithCache = function (f) { return host.readFile(f); };
var projectCompilerOptions = baseCompilerOptions;
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; });
- var originalGetSourceFile = compilerHost.getSourceFile;
- var computeHash = host.createHash || ts.generateDjb2Hash;
- updateGetSourceFile();
+ ts.setGetSourceFileAsHashVersioned(compilerHost, host);
+ var buildInfoChecked = createFileMap(toPath);
// Watch state
var builderPrograms = createFileMap(toPath);
var diagnostics = createFileMap(toPath);
@@ -91973,6 +93750,7 @@
projectStatus.clear();
missingRoots.clear();
globalDependencyGraph = undefined;
+ buildInfoChecked.clear();
diagnostics.clear();
projectPendingBuild.clear();
projectErrorsReported.clear();
@@ -91987,29 +93765,6 @@
ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); });
ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher);
builderPrograms.clear();
- updateGetSourceFile();
- }
- function updateGetSourceFile() {
- if (options.watch) {
- if (compilerHost.getSourceFile === originalGetSourceFile) {
- compilerHost.getSourceFile = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
- if (result && options.watch) {
- result.version = computeHash.call(host, result.text);
- }
- return result;
- };
- }
- }
- else {
- if (compilerHost.getSourceFile !== originalGetSourceFile) {
- compilerHost.getSourceFile = originalGetSourceFile;
- }
- }
}
function isParsedCommandLine(entry) {
return !!entry.options;
@@ -92160,13 +93915,14 @@
newestInputFileTime = inputTime;
}
}
- // Collect the expected outputs of this project
- var outputs = getAllProjectOutputs(project);
- if (outputs.length === 0) {
+ // Container if no files are specified in the project
+ if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) {
return {
type: UpToDateStatusType.ContainerOnly
};
}
+ // Collect the expected outputs of this project
+ var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
// Now see if all outputs are newer than the newest input
var oldestOutputFileName = "(none)";
var oldestOutputFileTime = maximumDate;
@@ -92241,6 +93997,8 @@
upstreamProjectName: ref.path
};
}
+ // Check oldest output file name only if there is no missing output file name
+ if (!missingOutputFileName) {
// 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) {
@@ -92262,6 +94020,7 @@
};
}
}
+ }
if (missingOutputFileName !== undefined) {
return {
type: UpToDateStatusType.OutputMissing,
@@ -92275,9 +94034,33 @@
newerInputFileName: newestInputFileName
};
}
+ else {
+ // Check tsconfig time
+ var configStatus = checkConfigFileUpToDateStatus(project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
+ if (configStatus)
+ return configStatus;
+ // Check extended config time
+ var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName); });
+ if (extendedConfigStatus)
+ return extendedConfigStatus;
+ }
+ if (!buildInfoChecked.hasKey(project.options.configFilePath)) {
+ buildInfoChecked.setValue(project.options.configFilePath, true);
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath) {
+ var value = readFileWithCache(buildInfoPath);
+ var buildInfo = value && ts.getBuildInfo(value);
+ if (buildInfo && buildInfo.version !== ts.version) {
+ return {
+ type: UpToDateStatusType.TsVersionOutputOfDate,
+ version: buildInfo.version
+ };
+ }
+ }
+ }
if (usesPrepend && pseudoUpToDate) {
return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
+ type: UpToDateStatusType.OutOfDateWithPrepend,
outOfDateOutputFileName: oldestOutputFileName,
newerProjectName: upstreamChangedProject
};
@@ -92293,6 +94076,17 @@
oldestOutputFileName: oldestOutputFileName
};
}
+ function checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName) {
+ // Check tsconfig time
+ var tsconfigTime = host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
+ if (oldestOutputFileTime < tsconfigTime) {
+ return {
+ type: UpToDateStatusType.OutOfDateWithSelf,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerInputFileName: configFile
+ };
+ }
+ }
function invalidateProject(configFileName, reloadLevel) {
invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel);
}
@@ -92411,7 +94205,9 @@
updateOutputTimestamps(proj);
return;
}
- var buildResult = buildSingleProject(resolved);
+ var buildResult = needsBuild(status, resolved) ?
+ buildSingleProject(resolved) : // Actual build
+ updateBundle(resolved); // Fake that files have been built by manipulating prepend and existing output
if (buildResult & BuildResultFlags.AnyErrors)
return;
var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue;
@@ -92427,18 +94223,27 @@
// If declaration output is changed, build the project
// otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
var status_1 = projectStatus.getValue(project);
- if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
- if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) {
+ if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
+ if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status_1.type === UpToDateStatusType.OutOfDateWithPrepend)) {
projectStatus.setValue(project, {
type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: status_1.oldestOutputFileName,
+ outOfDateOutputFileName: status_1.type === UpToDateStatusType.OutOfDateWithPrepend ? status_1.outOfDateOutputFileName : status_1.oldestOutputFileName,
newerProjectName: resolved
});
}
}
else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) {
+ if (prepend) {
+ projectStatus.setValue(project, {
+ type: UpToDateStatusType.OutOfDateWithPrepend,
+ outOfDateOutputFileName: status_1.oldestOutputFileName,
+ newerProjectName: resolved
+ });
+ }
+ else {
status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
}
+ }
addProjToQueue(project);
}
}
@@ -92494,8 +94299,7 @@
}
if (options.verbose)
reportStatus(ts.Diagnostics.Building_project_0, proj);
- var resultFlags = BuildResultFlags.None;
- resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
+ var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
var configFile = parseConfigFile(proj);
if (!configFile) {
// Failed to read the config file
@@ -92511,8 +94315,7 @@
}
// TODO: handle resolve module name to cache result in project reference redirect
projectCompilerOptions = configFile.options;
- var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences);
- projectCompilerOptions = baseCompilerOptions;
+ var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, getOldProgram(proj, configFile), configFile.errors, configFile.projectReferences);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
@@ -92568,17 +94371,19 @@
var status = {
type: UpToDateStatusType.UpToDate,
newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime,
- oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile)
+ oldestOutputFileName: outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(configFile, !host.useCaseSensitiveFileNames())
};
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
}
}
@@ -92591,15 +94396,71 @@
builderPrograms.setValue(proj, program);
}
}
+ function getOldProgram(proj, parsed) {
+ if (options.force)
+ return undefined;
+ var value = builderPrograms.getValue(proj);
+ if (value)
+ return value;
+ return ts.readBuilderProgram(parsed.options, readFileWithCache);
+ }
+ function updateBundle(proj) {
+ if (options.dry) {
+ reportStatus(ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
+ return BuildResultFlags.Success;
+ }
+ if (options.verbose)
+ reportStatus(ts.Diagnostics.Updating_output_of_project_0, proj);
+ // Update js, and source map
+ var config = ts.Debug.assertDefined(parseConfigFile(proj));
+ projectCompilerOptions = config.options;
+ var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) { return parseConfigFile(resolveProjectName(ref.path)); });
+ if (ts.isString(outputFiles)) {
+ reportStatus(ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
+ return buildSingleProject(proj);
+ }
+ // Actual Emit
+ ts.Debug.assert(!!outputFiles.length);
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ var emittedOutputs = createFileMap(toPath);
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
+ emittedOutputs.setValue(name, true);
+ ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
+ });
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
+ reportAndStoreErrors(proj, emitDiagnostics);
+ projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
+ }
+ // Update timestamps for dts
+ var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
+ oldestOutputFileName: outputFiles[0].name
+ };
+ diagnostics.removeKey(proj);
+ projectStatus.setValue(proj, status);
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged;
+ }
function updateOutputTimestamps(proj) {
if (options.dry) {
- return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
+ return reportStatus(ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
}
var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
- projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
+ oldestOutputFileName: ts.getFirstProjectOutput(proj, !host.useCaseSensitiveFileNames())
+ };
+ projectStatus.setValue(proj.options.configFilePath, status);
}
function updateOutputTimestampsWorker(proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
- var outputs = getAllProjectOutputs(proj);
+ var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
if (!skipOutputs || outputs.length !== skipOutputs.getSize()) {
if (options.verbose) {
reportStatus(verboseMessage, proj.options.configFilePath);
@@ -92633,7 +94494,7 @@
reportParseConfigFileDiagnostic(proj);
continue;
}
- var outputs = getAllProjectOutputs(parsed);
+ var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) {
var output = outputs_3[_b];
if (host.fileExists(output)) {
@@ -92720,7 +94581,9 @@
// Do nothing
continue;
}
- var buildResult = buildSingleProject(next);
+ var buildResult = needsBuild(status, next) ?
+ buildSingleProject(next) : // Actual build
+ updateBundle(next); // Fake that files have been built by manipulating prepend and existing output
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
@@ -92733,6 +94596,15 @@
readFileWithCache = savedReadFileWithCache;
return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success;
}
+ function needsBuild(status, configFile) {
+ if (status.type !== UpToDateStatusType.OutOfDateWithPrepend || options.force)
+ return true;
+ var config = parseConfigFile(configFile);
+ return !config ||
+ config.fileNames.length === 0 ||
+ !!config.errors.length ||
+ !ts.isIncrementalCompilation(config.options);
+ }
function reportParseConfigFileDiagnostic(proj) {
reportAndStoreErrors(proj, [configFileCache.getValue(proj)]);
}
@@ -92772,33 +94644,6 @@
return ts.combinePaths(project, "tsconfig.json");
}
ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
- function getAllProjectOutputs(project) {
- if (project.options.outFile || project.options.out) {
- 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 getFirstProjectOutput(project) {
- if (project.options.outFile || project.options.out) {
- return ts.first(getOutFileOutputs(project));
- }
- for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
- var inputFile = _a[_i];
- var outputs = getOutputFileNames(inputFile, project);
- if (outputs.length) {
- return ts.first(outputs);
- }
- }
- return ts.Debug.fail("project " + project.options.configFilePath + " expected to have at least one output");
- }
function formatUpToDateStatus(configFileName, status, relName, formatMessage) {
switch (status.type) {
case UpToDateStatusType.OutOfDateWithSelf:
@@ -92813,6 +94658,8 @@
}
// Don't report anything for "up to date because it was already built" -- too verbose
break;
+ case UpToDateStatusType.OutOfDateWithPrepend:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(configFileName), relName(status.newerProjectName));
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:
@@ -92821,6 +94668,8 @@
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.TsVersionOutputOfDate:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(configFileName), status.version, ts.version);
case UpToDateStatusType.ContainerOnly:
// Don't report status on "solution" projects
case UpToDateStatusType.ComputingUpstream:
@@ -92970,8 +94819,6 @@
}
}
})(ts || (ts = {}));
-//# sourceMappingURL=compiler.js.map
-"use strict";
/* @internal */
var ts;
(function (ts) {
@@ -92998,6 +94845,11 @@
* typingsInstaller will run the command with `${npmLocation} install ...`.
*/
Arguments.NpmLocation = "--npmLocation";
+ /**
+ * Flag indicating that the typings installer should try to validate the default npm location.
+ * If the default npm is not found when this flag is enabled, fallback to `npm install`
+ */
+ Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
})(Arguments = server.Arguments || (server.Arguments = {}));
function hasArgument(argumentName) {
return ts.sys.args.indexOf(argumentName) >= 0;
@@ -93312,8 +95164,6 @@
JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
})(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
})(ts || (ts = {}));
-//# sourceMappingURL=jsTyping.js.map
-"use strict";
var ts;
(function (ts) {
var server;
@@ -93790,7 +95640,6 @@
})(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
-//# sourceMappingURL=typingsInstallerCore.js.map
var ts;
(function (ts) {
var server;
@@ -93819,14 +95668,18 @@
}
return FileLog;
}());
- function getDefaultNPMLocation(processName) {
+ function getDefaultNPMLocation(processName, validateDefaultNpmLocation, host) {
if (path.basename(processName).indexOf("node") === 0) {
- return "\"" + path.join(path.dirname(process.argv[0]), "npm") + "\"";
+ var npmPath = path.join(path.dirname(process.argv[0]), "npm");
+ if (!validateDefaultNpmLocation) {
+ return npmPath;
}
- else {
- return "npm";
+ if (host.fileExists(npmPath)) {
+ return "\"" + npmPath + "\"";
}
}
+ return "npm";
+ }
function loadTypesRegistryFile(typesRegistryFilePath, host, log) {
if (!host.fileExists(typesRegistryFilePath)) {
if (log.isEnabled()) {
@@ -93851,15 +95704,16 @@
}
var NodeTypingsInstaller = (function (_super) {
__extends(NodeTypingsInstaller, _super);
- function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, throttleLimit, log) {
+ function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, throttleLimit, log) {
var _this = _super.call(this, ts.sys, globalTypingsCacheLocation, typingSafeListLocation ? ts.toPath(typingSafeListLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), typesMapLocation ? ts.toPath(typesMapLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typesMap.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log) || this;
- _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0]);
+ _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation, _this.installTypingHost);
if (ts.stringContains(_this.npmPath, " ") && _this.npmPath[0] !== "\"") {
_this.npmPath = "\"" + _this.npmPath + "\"";
}
if (_this.log.isEnabled()) {
_this.log.writeLine("Process id: " + process.pid);
_this.log.writeLine("NPM location: " + _this.npmPath + " (explicit '" + server.Arguments.NpmLocation + "' " + (npmLocation === undefined ? "not " : "") + " provided)");
+ _this.log.writeLine("validateDefaultNpmLocation: " + validateDefaultNpmLocation);
}
(_this.nodeExecSync = require("child_process").execSync);
_this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
@@ -93986,6 +95840,7 @@
var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation);
var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation);
var npmLocation = server.findArgument(server.Arguments.NpmLocation);
+ var validateDefaultNpmLocation = server.hasArgument(server.Arguments.ValidateDefaultNpmLocation);
var log = new FileLog(logFilePath);
if (log.isEnabled()) {
process.on("uncaughtException", function (e) {
@@ -93998,7 +95853,7 @@
}
process.exit(0);
});
- var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, 5, log);
+ var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, 5, log);
installer.listen();
function indent(newline, str) {
return newline + " " + str.replace(/\r?\n/, newline + " ");

package.json

@@ -2,7 +2,7 @@
"name": "typescript",
"author": "Microsoft Corp.",
"homepage": "https://www.typescriptlang.org/",
- "version": "3.3.4000",
+ "version": "3.4.5",
"license": "Apache-2.0",
"description": "TypeScript is a language for application scale JavaScript development",
"keywords": [
@@ -35,10 +35,8 @@
"@types/convert-source-map": "latest",
"@types/del": "latest",
"@types/glob": "latest",
- "@types/gulp": "3.X",
+ "@types/gulp": "^4.0.5",
"@types/gulp-concat": "latest",
- "@types/gulp-help": "latest",
- "@types/gulp-if": "0.0.33",
"@types/gulp-newer": "latest",
"@types/gulp-rename": "0.0.33",
"@types/gulp-sourcemaps": "0.0.32",
@@ -48,9 +46,9 @@
"@types/minimist": "latest",
"@types/mkdirp": "latest",
"@types/mocha": "latest",
+ "@types/ms": "latest",
"@types/node": "8.5.5",
"@types/q": "latest",
- "@types/run-sequence": "latest",
"@types/source-map-support": "latest",
"@types/through2": "latest",
"@types/travis-fold": "latest",
@@ -63,30 +61,25 @@
"del": "latest",
"fancy-log": "latest",
"fs-extra": "^6.0.1",
- "gulp": "3.X",
- "gulp-clone": "latest",
+ "gulp": "^4.0.0",
"gulp-concat": "latest",
- "gulp-help": "latest",
- "gulp-if": "latest",
"gulp-insert": "latest",
"gulp-newer": "latest",
"gulp-rename": "latest",
"gulp-sourcemaps": "latest",
- "gulp-typescript": "latest",
"istanbul": "latest",
- "jake": "latest",
- "lodash": "4.17.10",
+ "lodash": "^4.17.11",
"merge2": "latest",
"minimist": "latest",
"mkdirp": "latest",
"mocha": "latest",
"mocha-fivemat-progress-reporter": "latest",
+ "ms": "latest",
"plugin-error": "latest",
"pretty-hrtime": "^1.0.3",
"prex": "^0.4.3",
"q": "latest",
"remove-internal": "^2.9.2",
- "run-sequence": "latest",
"source-map-support": "latest",
"through2": "latest",
"travis-fold": "latest",
@@ -97,16 +90,16 @@
"xml2js": "^0.4.19"
},
"scripts": {
- "pretest": "jake tests",
- "test": "jake runtests-parallel light=false",
+ "pretest": "gulp tests",
+ "test": "gulp runtests-parallel --light=false",
"build": "npm run build:compiler && npm run build:tests",
- "build:compiler": "jake local",
- "build:tests": "jake tests",
+ "build:compiler": "gulp local",
+ "build:tests": "gulp tests",
"start": "node lib/tsc",
- "clean": "jake clean",
+ "clean": "gulp clean",
"gulp": "gulp",
- "jake": "jake",
- "lint": "jake lint",
+ "jake": "gulp",
+ "lint": "gulp lint",
"setup-hooks": "node scripts/link-hooks.js"
},
"browser": {

README.md

@@ -61,29 +61,29 @@
cd TypeScript
```
-Install [Jake](http://jakejs.com/) tools and dev dependencies:
+Install [Gulp](https://gulpjs.com/) tools and dev dependencies:
```bash
-npm install -g jake
+npm install -g gulp
npm install
```
Use one of the following to build and test:
```
-jake local # Build the compiler into built/local
-jake clean # Delete the built compiler
-jake LKG # Replace the last known good with the built one.
+gulp local # Build the compiler into built/local
+gulp clean # Delete the built compiler
+gulp LKG # Replace the last known good with the built one.
# Bootstrapping step to be executed when the built compiler reaches a stable state.
-jake tests # Build the test infrastructure using the built compiler.
-jake runtests # Run tests using the built compiler and test infrastructure.
+gulp tests # Build the test infrastructure using the built compiler.
+gulp runtests # Run tests using the built compiler and test infrastructure.
# You can override the host or specify a test for this command.
- # Use host=<hostName> or tests=<testPath>.
-jake runtests-browser # Runs the tests using the built run.js file. Syntax is jake runtests. Optional
- parameters 'host=', 'tests=[regex], reporter=[list|spec|json|<more>]'.
-jake baseline-accept # This replaces the baseline test results with the results obtained from jake runtests.
-jake lint # Runs tslint on the TypeScript source.
-jake help # List the above commands.
+ # Use --host=<hostName> or --tests=<testPath>.
+gulp runtests-browser # Runs the tests using the built run.js file. Syntax is gulp runtests. Optional
+ parameters '--host=', '--tests=[regex], --reporter=[list|spec|json|<more>]'.
+gulp baseline-accept # This replaces the baseline test results with the results obtained from gulp runtests.
+gulp lint # Runs tslint on the TypeScript source.
+gulp help # List the above commands.
```