Merge branch 'master' into map4

This commit is contained in:
Andy Hanson
2016-10-17 06:49:53 -07:00
336 changed files with 35313 additions and 16147 deletions
+2
View File
@@ -41,7 +41,9 @@ tests/cases/**/*.js.map
scripts/debug.bat
scripts/run.bat
scripts/word2md.js
scripts/buildProtocol.js
scripts/ior.js
scripts/buildProtocol.js
scripts/*.js.map
scripts/typings/
coverage/
+49 -13
View File
@@ -71,13 +71,14 @@ var compilerSources = [
"visitor.ts",
"transformers/destructuring.ts",
"transformers/ts.ts",
"transformers/module/es6.ts",
"transformers/module/es2015.ts",
"transformers/module/system.ts",
"transformers/module/module.ts",
"transformers/jsx.ts",
"transformers/es7.ts",
"transformers/es2017.ts",
"transformers/es2016.ts",
"transformers/es2015.ts",
"transformers/generators.ts",
"transformers/es6.ts",
"transformer.ts",
"sourcemap.ts",
"comments.ts",
@@ -106,13 +107,14 @@ var servicesSources = [
"visitor.ts",
"transformers/destructuring.ts",
"transformers/ts.ts",
"transformers/module/es6.ts",
"transformers/module/es2015.ts",
"transformers/module/system.ts",
"transformers/module/module.ts",
"transformers/jsx.ts",
"transformers/es7.ts",
"transformers/es2017.ts",
"transformers/es2016.ts",
"transformers/es2015.ts",
"transformers/generators.ts",
"transformers/es6.ts",
"transformer.ts",
"sourcemap.ts",
"comments.ts",
@@ -176,7 +178,7 @@ var serverCoreSources = [
"lsHost.ts",
"project.ts",
"editorServices.ts",
"protocol.d.ts",
"protocol.ts",
"session.ts",
"server.ts"
].map(function (f) {
@@ -200,14 +202,13 @@ var typingsInstallerSources = [
var serverSources = serverCoreSources.concat(servicesSources);
var languageServiceLibrarySources = [
"protocol.d.ts",
"protocol.ts",
"utilities.ts",
"scriptVersionCache.ts",
"scriptInfo.ts",
"lsHost.ts",
"project.ts",
"editorServices.ts",
"protocol.d.ts",
"session.ts",
].map(function (f) {
@@ -261,7 +262,7 @@ var harnessSources = harnessCoreSources.concat([
].map(function (f) {
return path.join(unittestsDirectory, f);
})).concat([
"protocol.d.ts",
"protocol.ts",
"utilities.ts",
"scriptVersionCache.ts",
"scriptInfo.ts",
@@ -269,7 +270,6 @@ var harnessSources = harnessCoreSources.concat([
"project.ts",
"typingsCache.ts",
"editorServices.ts",
"protocol.d.ts",
"session.ts",
].map(function (f) {
return path.join(serverDirectory, f);
@@ -520,6 +520,40 @@ compileFile(processDiagnosticMessagesJs,
[],
/*useBuiltCompiler*/ false);
var buildProtocolTs = path.join(scriptsDirectory, "buildProtocol.ts");
var buildProtocolJs = path.join(scriptsDirectory, "buildProtocol.js");
var buildProtocolDts = path.join(builtLocalDirectory, "protocol.d.ts");
var typescriptServicesDts = path.join(builtLocalDirectory, "typescriptServices.d.ts");
file(buildProtocolTs);
compileFile(buildProtocolJs,
[buildProtocolTs],
[buildProtocolTs],
[],
/*useBuiltCompiler*/ false,
{noOutFile: true});
file(buildProtocolDts, [buildProtocolTs, buildProtocolJs, typescriptServicesDts], function() {
var protocolTs = path.join(serverDirectory, "protocol.ts");
var cmd = host + " " + buildProtocolJs + " "+ protocolTs + " " + typescriptServicesDts + " " + buildProtocolDts;
console.log(cmd);
var ex = jake.createExec([cmd]);
// Add listeners for output and error
ex.addListener("stdout", function (output) {
process.stdout.write(output);
});
ex.addListener("stderr", function (error) {
process.stderr.write(error);
});
ex.addListener("cmdEnd", function () {
complete();
});
ex.run();
}, { async: true })
// The generated diagnostics map; built for the compiler and for the 'generate-diagnostics' task
file(diagnosticInfoMapTs, [processDiagnosticMessagesJs, diagnosticMessagesJson], function () {
var cmd = host + " " + processDiagnosticMessagesJs + " " + diagnosticMessagesJson;
@@ -657,6 +691,8 @@ compileFile(
inlineSourceMap: true
});
file(typescriptServicesDts, [servicesFile]);
var cancellationTokenFile = path.join(builtLocalDirectory, "cancellationToken.js");
compileFile(cancellationTokenFile, cancellationTokenSources, [builtLocalDirectory].concat(cancellationTokenSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, { outDir: builtLocalDirectory, noOutFile: true });
@@ -691,7 +727,7 @@ task("build-fold-end", [], function () {
// Local target to build the compiler and services
desc("Builds the full compiler and services");
task("local", ["build-fold-start", "generate-diagnostics", "lib", tscFile, servicesFile, nodeDefinitionsFile, serverFile, builtGeneratedDiagnosticMessagesJSON, "lssl", "build-fold-end"]);
task("local", ["build-fold-start", "generate-diagnostics", "lib", tscFile, servicesFile, nodeDefinitionsFile, serverFile, buildProtocolDts, builtGeneratedDiagnosticMessagesJSON, "lssl", "build-fold-end"]);
// Local target to build only tsc.js
desc("Builds only the compiler");
@@ -747,7 +783,7 @@ task("generate-spec", [specMd]);
// Makes a new LKG. This target does not build anything, but errors if not all the outputs are present in the built/local directory
desc("Makes a new LKG out of the built js files");
task("LKG", ["clean", "release", "local"].concat(libraryTargets), function () {
var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile, cancellationTokenFile, typingsInstallerFile].concat(libraryTargets);
var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile, cancellationTokenFile, typingsInstallerFile, buildProtocolDts].concat(libraryTargets);
var missingFiles = expectedFiles.filter(function (f) {
return !fs.existsSync(f);
});
+1 -1
View File
@@ -2,7 +2,7 @@
<!-- QUESTIONS: This is not a general support forum! Ask Qs at http://stackoverflow.com/questions/tagged/typescript -->
<!-- SUGGESTIONS: See https://github.com/Microsoft/TypeScript-wiki/blob/master/Writing-Good-Design-Proposals.md -->
**TypeScript Version:** 1.8.0 / nightly (2.0.0-dev.201xxxxx)
**TypeScript Version:** 2.0.3 / nightly (2.1.0-dev.201xxxxx)
**Code**
+217 -189
View File
@@ -260,6 +260,9 @@ interface Function {
*/
bind(this: Function, thisArg: any, ...argArray: any[]): any;
/** Returns a string representation of a function. */
toString(): string;
prototype: any;
readonly length: number;
@@ -1216,6 +1219,30 @@ interface Array<T> {
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
@@ -11660,11 +11687,12 @@ declare var HashChangeEvent: {
interface History {
readonly length: number;
readonly state: any;
back(distance?: any): void;
forward(distance?: any): void;
go(delta?: any): void;
pushState(statedata: any, title?: string, url?: string): void;
replaceState(statedata: any, title?: string, url?: string): void;
scrollRestoration: ScrollRestoration;
back(): void;
forward(): void;
go(delta?: number): void;
pushState(data: any, title: string, url?: string | null): void;
replaceState(data: any, title: string, url?: string | null): void;
}
declare var History: {
@@ -17236,7 +17264,6 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
[index: number]: Window;
}
declare var Window: {
@@ -17267,7 +17294,7 @@ declare var XMLDocument: {
}
interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
onreadystatechange: (this: this, ev: ProgressEvent) => any;
onreadystatechange: (this: this, ev: Event) => any;
readonly readyState: number;
readonly response: any;
readonly responseText: string;
@@ -17294,13 +17321,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -17641,183 +17668,183 @@ interface NavigatorUserMedia {
}
interface NodeSelector {
querySelector(selectors: "a"): HTMLAnchorElement;
querySelector(selectors: "abbr"): HTMLElement;
querySelector(selectors: "acronym"): HTMLElement;
querySelector(selectors: "address"): HTMLElement;
querySelector(selectors: "applet"): HTMLAppletElement;
querySelector(selectors: "area"): HTMLAreaElement;
querySelector(selectors: "article"): HTMLElement;
querySelector(selectors: "aside"): HTMLElement;
querySelector(selectors: "audio"): HTMLAudioElement;
querySelector(selectors: "b"): HTMLElement;
querySelector(selectors: "base"): HTMLBaseElement;
querySelector(selectors: "basefont"): HTMLBaseFontElement;
querySelector(selectors: "bdo"): HTMLElement;
querySelector(selectors: "big"): HTMLElement;
querySelector(selectors: "blockquote"): HTMLQuoteElement;
querySelector(selectors: "body"): HTMLBodyElement;
querySelector(selectors: "br"): HTMLBRElement;
querySelector(selectors: "button"): HTMLButtonElement;
querySelector(selectors: "canvas"): HTMLCanvasElement;
querySelector(selectors: "caption"): HTMLTableCaptionElement;
querySelector(selectors: "center"): HTMLElement;
querySelector(selectors: "circle"): SVGCircleElement;
querySelector(selectors: "cite"): HTMLElement;
querySelector(selectors: "clippath"): SVGClipPathElement;
querySelector(selectors: "code"): HTMLElement;
querySelector(selectors: "col"): HTMLTableColElement;
querySelector(selectors: "colgroup"): HTMLTableColElement;
querySelector(selectors: "datalist"): HTMLDataListElement;
querySelector(selectors: "dd"): HTMLElement;
querySelector(selectors: "defs"): SVGDefsElement;
querySelector(selectors: "del"): HTMLModElement;
querySelector(selectors: "desc"): SVGDescElement;
querySelector(selectors: "dfn"): HTMLElement;
querySelector(selectors: "dir"): HTMLDirectoryElement;
querySelector(selectors: "div"): HTMLDivElement;
querySelector(selectors: "dl"): HTMLDListElement;
querySelector(selectors: "dt"): HTMLElement;
querySelector(selectors: "ellipse"): SVGEllipseElement;
querySelector(selectors: "em"): HTMLElement;
querySelector(selectors: "embed"): HTMLEmbedElement;
querySelector(selectors: "feblend"): SVGFEBlendElement;
querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement;
querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement;
querySelector(selectors: "fecomposite"): SVGFECompositeElement;
querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement;
querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement;
querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement;
querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement;
querySelector(selectors: "feflood"): SVGFEFloodElement;
querySelector(selectors: "fefunca"): SVGFEFuncAElement;
querySelector(selectors: "fefuncb"): SVGFEFuncBElement;
querySelector(selectors: "fefuncg"): SVGFEFuncGElement;
querySelector(selectors: "fefuncr"): SVGFEFuncRElement;
querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement;
querySelector(selectors: "feimage"): SVGFEImageElement;
querySelector(selectors: "femerge"): SVGFEMergeElement;
querySelector(selectors: "femergenode"): SVGFEMergeNodeElement;
querySelector(selectors: "femorphology"): SVGFEMorphologyElement;
querySelector(selectors: "feoffset"): SVGFEOffsetElement;
querySelector(selectors: "fepointlight"): SVGFEPointLightElement;
querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement;
querySelector(selectors: "fespotlight"): SVGFESpotLightElement;
querySelector(selectors: "fetile"): SVGFETileElement;
querySelector(selectors: "feturbulence"): SVGFETurbulenceElement;
querySelector(selectors: "fieldset"): HTMLFieldSetElement;
querySelector(selectors: "figcaption"): HTMLElement;
querySelector(selectors: "figure"): HTMLElement;
querySelector(selectors: "filter"): SVGFilterElement;
querySelector(selectors: "font"): HTMLFontElement;
querySelector(selectors: "footer"): HTMLElement;
querySelector(selectors: "foreignobject"): SVGForeignObjectElement;
querySelector(selectors: "form"): HTMLFormElement;
querySelector(selectors: "frame"): HTMLFrameElement;
querySelector(selectors: "frameset"): HTMLFrameSetElement;
querySelector(selectors: "g"): SVGGElement;
querySelector(selectors: "h1"): HTMLHeadingElement;
querySelector(selectors: "h2"): HTMLHeadingElement;
querySelector(selectors: "h3"): HTMLHeadingElement;
querySelector(selectors: "h4"): HTMLHeadingElement;
querySelector(selectors: "h5"): HTMLHeadingElement;
querySelector(selectors: "h6"): HTMLHeadingElement;
querySelector(selectors: "head"): HTMLHeadElement;
querySelector(selectors: "header"): HTMLElement;
querySelector(selectors: "hgroup"): HTMLElement;
querySelector(selectors: "hr"): HTMLHRElement;
querySelector(selectors: "html"): HTMLHtmlElement;
querySelector(selectors: "i"): HTMLElement;
querySelector(selectors: "iframe"): HTMLIFrameElement;
querySelector(selectors: "image"): SVGImageElement;
querySelector(selectors: "img"): HTMLImageElement;
querySelector(selectors: "input"): HTMLInputElement;
querySelector(selectors: "ins"): HTMLModElement;
querySelector(selectors: "isindex"): HTMLUnknownElement;
querySelector(selectors: "kbd"): HTMLElement;
querySelector(selectors: "keygen"): HTMLElement;
querySelector(selectors: "label"): HTMLLabelElement;
querySelector(selectors: "legend"): HTMLLegendElement;
querySelector(selectors: "li"): HTMLLIElement;
querySelector(selectors: "line"): SVGLineElement;
querySelector(selectors: "lineargradient"): SVGLinearGradientElement;
querySelector(selectors: "link"): HTMLLinkElement;
querySelector(selectors: "listing"): HTMLPreElement;
querySelector(selectors: "map"): HTMLMapElement;
querySelector(selectors: "mark"): HTMLElement;
querySelector(selectors: "marker"): SVGMarkerElement;
querySelector(selectors: "marquee"): HTMLMarqueeElement;
querySelector(selectors: "mask"): SVGMaskElement;
querySelector(selectors: "menu"): HTMLMenuElement;
querySelector(selectors: "meta"): HTMLMetaElement;
querySelector(selectors: "metadata"): SVGMetadataElement;
querySelector(selectors: "meter"): HTMLMeterElement;
querySelector(selectors: "nav"): HTMLElement;
querySelector(selectors: "nextid"): HTMLUnknownElement;
querySelector(selectors: "nobr"): HTMLElement;
querySelector(selectors: "noframes"): HTMLElement;
querySelector(selectors: "noscript"): HTMLElement;
querySelector(selectors: "object"): HTMLObjectElement;
querySelector(selectors: "ol"): HTMLOListElement;
querySelector(selectors: "optgroup"): HTMLOptGroupElement;
querySelector(selectors: "option"): HTMLOptionElement;
querySelector(selectors: "p"): HTMLParagraphElement;
querySelector(selectors: "param"): HTMLParamElement;
querySelector(selectors: "path"): SVGPathElement;
querySelector(selectors: "pattern"): SVGPatternElement;
querySelector(selectors: "picture"): HTMLPictureElement;
querySelector(selectors: "plaintext"): HTMLElement;
querySelector(selectors: "polygon"): SVGPolygonElement;
querySelector(selectors: "polyline"): SVGPolylineElement;
querySelector(selectors: "pre"): HTMLPreElement;
querySelector(selectors: "progress"): HTMLProgressElement;
querySelector(selectors: "q"): HTMLQuoteElement;
querySelector(selectors: "radialgradient"): SVGRadialGradientElement;
querySelector(selectors: "rect"): SVGRectElement;
querySelector(selectors: "rt"): HTMLElement;
querySelector(selectors: "ruby"): HTMLElement;
querySelector(selectors: "s"): HTMLElement;
querySelector(selectors: "samp"): HTMLElement;
querySelector(selectors: "script"): HTMLScriptElement;
querySelector(selectors: "section"): HTMLElement;
querySelector(selectors: "select"): HTMLSelectElement;
querySelector(selectors: "small"): HTMLElement;
querySelector(selectors: "source"): HTMLSourceElement;
querySelector(selectors: "span"): HTMLSpanElement;
querySelector(selectors: "stop"): SVGStopElement;
querySelector(selectors: "strike"): HTMLElement;
querySelector(selectors: "strong"): HTMLElement;
querySelector(selectors: "style"): HTMLStyleElement;
querySelector(selectors: "sub"): HTMLElement;
querySelector(selectors: "sup"): HTMLElement;
querySelector(selectors: "svg"): SVGSVGElement;
querySelector(selectors: "switch"): SVGSwitchElement;
querySelector(selectors: "symbol"): SVGSymbolElement;
querySelector(selectors: "table"): HTMLTableElement;
querySelector(selectors: "tbody"): HTMLTableSectionElement;
querySelector(selectors: "td"): HTMLTableDataCellElement;
querySelector(selectors: "template"): HTMLTemplateElement;
querySelector(selectors: "text"): SVGTextElement;
querySelector(selectors: "textpath"): SVGTextPathElement;
querySelector(selectors: "textarea"): HTMLTextAreaElement;
querySelector(selectors: "tfoot"): HTMLTableSectionElement;
querySelector(selectors: "th"): HTMLTableHeaderCellElement;
querySelector(selectors: "thead"): HTMLTableSectionElement;
querySelector(selectors: "title"): HTMLTitleElement;
querySelector(selectors: "tr"): HTMLTableRowElement;
querySelector(selectors: "track"): HTMLTrackElement;
querySelector(selectors: "tspan"): SVGTSpanElement;
querySelector(selectors: "tt"): HTMLElement;
querySelector(selectors: "u"): HTMLElement;
querySelector(selectors: "ul"): HTMLUListElement;
querySelector(selectors: "use"): SVGUseElement;
querySelector(selectors: "var"): HTMLElement;
querySelector(selectors: "video"): HTMLVideoElement;
querySelector(selectors: "view"): SVGViewElement;
querySelector(selectors: "wbr"): HTMLElement;
querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement;
querySelector(selectors: "xmp"): HTMLPreElement;
querySelector(selectors: string): Element;
querySelector(selectors: "a"): HTMLAnchorElement | null;
querySelector(selectors: "abbr"): HTMLElement | null;
querySelector(selectors: "acronym"): HTMLElement | null;
querySelector(selectors: "address"): HTMLElement | null;
querySelector(selectors: "applet"): HTMLAppletElement | null;
querySelector(selectors: "area"): HTMLAreaElement | null;
querySelector(selectors: "article"): HTMLElement | null;
querySelector(selectors: "aside"): HTMLElement | null;
querySelector(selectors: "audio"): HTMLAudioElement | null;
querySelector(selectors: "b"): HTMLElement | null;
querySelector(selectors: "base"): HTMLBaseElement | null;
querySelector(selectors: "basefont"): HTMLBaseFontElement | null;
querySelector(selectors: "bdo"): HTMLElement | null;
querySelector(selectors: "big"): HTMLElement | null;
querySelector(selectors: "blockquote"): HTMLQuoteElement | null;
querySelector(selectors: "body"): HTMLBodyElement | null;
querySelector(selectors: "br"): HTMLBRElement | null;
querySelector(selectors: "button"): HTMLButtonElement | null;
querySelector(selectors: "canvas"): HTMLCanvasElement | null;
querySelector(selectors: "caption"): HTMLTableCaptionElement | null;
querySelector(selectors: "center"): HTMLElement | null;
querySelector(selectors: "circle"): SVGCircleElement | null;
querySelector(selectors: "cite"): HTMLElement | null;
querySelector(selectors: "clippath"): SVGClipPathElement | null;
querySelector(selectors: "code"): HTMLElement | null;
querySelector(selectors: "col"): HTMLTableColElement | null;
querySelector(selectors: "colgroup"): HTMLTableColElement | null;
querySelector(selectors: "datalist"): HTMLDataListElement | null;
querySelector(selectors: "dd"): HTMLElement | null;
querySelector(selectors: "defs"): SVGDefsElement | null;
querySelector(selectors: "del"): HTMLModElement | null;
querySelector(selectors: "desc"): SVGDescElement | null;
querySelector(selectors: "dfn"): HTMLElement | null;
querySelector(selectors: "dir"): HTMLDirectoryElement | null;
querySelector(selectors: "div"): HTMLDivElement | null;
querySelector(selectors: "dl"): HTMLDListElement | null;
querySelector(selectors: "dt"): HTMLElement | null;
querySelector(selectors: "ellipse"): SVGEllipseElement | null;
querySelector(selectors: "em"): HTMLElement | null;
querySelector(selectors: "embed"): HTMLEmbedElement | null;
querySelector(selectors: "feblend"): SVGFEBlendElement | null;
querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement | null;
querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement | null;
querySelector(selectors: "fecomposite"): SVGFECompositeElement | null;
querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement | null;
querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement | null;
querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement | null;
querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement | null;
querySelector(selectors: "feflood"): SVGFEFloodElement | null;
querySelector(selectors: "fefunca"): SVGFEFuncAElement | null;
querySelector(selectors: "fefuncb"): SVGFEFuncBElement | null;
querySelector(selectors: "fefuncg"): SVGFEFuncGElement | null;
querySelector(selectors: "fefuncr"): SVGFEFuncRElement | null;
querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement | null;
querySelector(selectors: "feimage"): SVGFEImageElement | null;
querySelector(selectors: "femerge"): SVGFEMergeElement | null;
querySelector(selectors: "femergenode"): SVGFEMergeNodeElement | null;
querySelector(selectors: "femorphology"): SVGFEMorphologyElement | null;
querySelector(selectors: "feoffset"): SVGFEOffsetElement | null;
querySelector(selectors: "fepointlight"): SVGFEPointLightElement | null;
querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement | null;
querySelector(selectors: "fespotlight"): SVGFESpotLightElement | null;
querySelector(selectors: "fetile"): SVGFETileElement | null;
querySelector(selectors: "feturbulence"): SVGFETurbulenceElement | null;
querySelector(selectors: "fieldset"): HTMLFieldSetElement | null;
querySelector(selectors: "figcaption"): HTMLElement | null;
querySelector(selectors: "figure"): HTMLElement | null;
querySelector(selectors: "filter"): SVGFilterElement | null;
querySelector(selectors: "font"): HTMLFontElement | null;
querySelector(selectors: "footer"): HTMLElement | null;
querySelector(selectors: "foreignobject"): SVGForeignObjectElement | null;
querySelector(selectors: "form"): HTMLFormElement | null;
querySelector(selectors: "frame"): HTMLFrameElement | null;
querySelector(selectors: "frameset"): HTMLFrameSetElement | null;
querySelector(selectors: "g"): SVGGElement | null;
querySelector(selectors: "h1"): HTMLHeadingElement | null;
querySelector(selectors: "h2"): HTMLHeadingElement | null;
querySelector(selectors: "h3"): HTMLHeadingElement | null;
querySelector(selectors: "h4"): HTMLHeadingElement | null;
querySelector(selectors: "h5"): HTMLHeadingElement | null;
querySelector(selectors: "h6"): HTMLHeadingElement | null;
querySelector(selectors: "head"): HTMLHeadElement | null;
querySelector(selectors: "header"): HTMLElement | null;
querySelector(selectors: "hgroup"): HTMLElement | null;
querySelector(selectors: "hr"): HTMLHRElement | null;
querySelector(selectors: "html"): HTMLHtmlElement | null;
querySelector(selectors: "i"): HTMLElement | null;
querySelector(selectors: "iframe"): HTMLIFrameElement | null;
querySelector(selectors: "image"): SVGImageElement | null;
querySelector(selectors: "img"): HTMLImageElement | null;
querySelector(selectors: "input"): HTMLInputElement | null;
querySelector(selectors: "ins"): HTMLModElement | null;
querySelector(selectors: "isindex"): HTMLUnknownElement | null;
querySelector(selectors: "kbd"): HTMLElement | null;
querySelector(selectors: "keygen"): HTMLElement | null;
querySelector(selectors: "label"): HTMLLabelElement | null;
querySelector(selectors: "legend"): HTMLLegendElement | null;
querySelector(selectors: "li"): HTMLLIElement | null;
querySelector(selectors: "line"): SVGLineElement | null;
querySelector(selectors: "lineargradient"): SVGLinearGradientElement | null;
querySelector(selectors: "link"): HTMLLinkElement | null;
querySelector(selectors: "listing"): HTMLPreElement | null;
querySelector(selectors: "map"): HTMLMapElement | null;
querySelector(selectors: "mark"): HTMLElement | null;
querySelector(selectors: "marker"): SVGMarkerElement | null;
querySelector(selectors: "marquee"): HTMLMarqueeElement | null;
querySelector(selectors: "mask"): SVGMaskElement | null;
querySelector(selectors: "menu"): HTMLMenuElement | null;
querySelector(selectors: "meta"): HTMLMetaElement | null;
querySelector(selectors: "metadata"): SVGMetadataElement | null;
querySelector(selectors: "meter"): HTMLMeterElement | null;
querySelector(selectors: "nav"): HTMLElement | null;
querySelector(selectors: "nextid"): HTMLUnknownElement | null;
querySelector(selectors: "nobr"): HTMLElement | null;
querySelector(selectors: "noframes"): HTMLElement | null;
querySelector(selectors: "noscript"): HTMLElement | null;
querySelector(selectors: "object"): HTMLObjectElement | null;
querySelector(selectors: "ol"): HTMLOListElement | null;
querySelector(selectors: "optgroup"): HTMLOptGroupElement | null;
querySelector(selectors: "option"): HTMLOptionElement | null;
querySelector(selectors: "p"): HTMLParagraphElement | null;
querySelector(selectors: "param"): HTMLParamElement | null;
querySelector(selectors: "path"): SVGPathElement | null;
querySelector(selectors: "pattern"): SVGPatternElement | null;
querySelector(selectors: "picture"): HTMLPictureElement | null;
querySelector(selectors: "plaintext"): HTMLElement | null;
querySelector(selectors: "polygon"): SVGPolygonElement | null;
querySelector(selectors: "polyline"): SVGPolylineElement | null;
querySelector(selectors: "pre"): HTMLPreElement | null;
querySelector(selectors: "progress"): HTMLProgressElement | null;
querySelector(selectors: "q"): HTMLQuoteElement | null;
querySelector(selectors: "radialgradient"): SVGRadialGradientElement | null;
querySelector(selectors: "rect"): SVGRectElement | null;
querySelector(selectors: "rt"): HTMLElement | null;
querySelector(selectors: "ruby"): HTMLElement | null;
querySelector(selectors: "s"): HTMLElement | null;
querySelector(selectors: "samp"): HTMLElement | null;
querySelector(selectors: "script"): HTMLScriptElement | null;
querySelector(selectors: "section"): HTMLElement | null;
querySelector(selectors: "select"): HTMLSelectElement | null;
querySelector(selectors: "small"): HTMLElement | null;
querySelector(selectors: "source"): HTMLSourceElement | null;
querySelector(selectors: "span"): HTMLSpanElement | null;
querySelector(selectors: "stop"): SVGStopElement | null;
querySelector(selectors: "strike"): HTMLElement | null;
querySelector(selectors: "strong"): HTMLElement | null;
querySelector(selectors: "style"): HTMLStyleElement | null;
querySelector(selectors: "sub"): HTMLElement | null;
querySelector(selectors: "sup"): HTMLElement | null;
querySelector(selectors: "svg"): SVGSVGElement | null;
querySelector(selectors: "switch"): SVGSwitchElement | null;
querySelector(selectors: "symbol"): SVGSymbolElement | null;
querySelector(selectors: "table"): HTMLTableElement | null;
querySelector(selectors: "tbody"): HTMLTableSectionElement | null;
querySelector(selectors: "td"): HTMLTableDataCellElement | null;
querySelector(selectors: "template"): HTMLTemplateElement | null;
querySelector(selectors: "text"): SVGTextElement | null;
querySelector(selectors: "textpath"): SVGTextPathElement | null;
querySelector(selectors: "textarea"): HTMLTextAreaElement | null;
querySelector(selectors: "tfoot"): HTMLTableSectionElement | null;
querySelector(selectors: "th"): HTMLTableHeaderCellElement | null;
querySelector(selectors: "thead"): HTMLTableSectionElement | null;
querySelector(selectors: "title"): HTMLTitleElement | null;
querySelector(selectors: "tr"): HTMLTableRowElement | null;
querySelector(selectors: "track"): HTMLTrackElement | null;
querySelector(selectors: "tspan"): SVGTSpanElement | null;
querySelector(selectors: "tt"): HTMLElement | null;
querySelector(selectors: "u"): HTMLElement | null;
querySelector(selectors: "ul"): HTMLUListElement | null;
querySelector(selectors: "use"): SVGUseElement | null;
querySelector(selectors: "var"): HTMLElement | null;
querySelector(selectors: "video"): HTMLVideoElement | null;
querySelector(selectors: "view"): SVGViewElement | null;
querySelector(selectors: "wbr"): HTMLElement | null;
querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement | null;
querySelector(selectors: "xmp"): HTMLPreElement | null;
querySelector(selectors: string): Element | null;
querySelectorAll(selectors: "a"): NodeListOf<HTMLAnchorElement>;
querySelectorAll(selectors: "abbr"): NodeListOf<HTMLElement>;
querySelectorAll(selectors: "acronym"): NodeListOf<HTMLElement>;
@@ -18747,6 +18774,7 @@ type ScrollLogicalPosition = "start" | "center" | "end" | "nearest";
type IDBValidKey = number | string | Date | IDBArrayKey;
type BufferSource = ArrayBuffer | ArrayBufferView;
type MouseWheelEvent = WheelEvent;
type ScrollRestoration = "auto" | "manual";
/////////////////////////////
/// WorkerGlobalScope APIs
/////////////////////////////
+191 -190
View File
@@ -7552,11 +7552,12 @@ declare var HashChangeEvent: {
interface History {
readonly length: number;
readonly state: any;
back(distance?: any): void;
forward(distance?: any): void;
go(delta?: any): void;
pushState(statedata: any, title?: string, url?: string): void;
replaceState(statedata: any, title?: string, url?: string): void;
scrollRestoration: ScrollRestoration;
back(): void;
forward(): void;
go(delta?: number): void;
pushState(data: any, title: string, url?: string | null): void;
replaceState(data: any, title: string, url?: string | null): void;
}
declare var History: {
@@ -13128,7 +13129,6 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
[index: number]: Window;
}
declare var Window: {
@@ -13159,7 +13159,7 @@ declare var XMLDocument: {
}
interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
onreadystatechange: (this: this, ev: ProgressEvent) => any;
onreadystatechange: (this: this, ev: Event) => any;
readonly readyState: number;
readonly response: any;
readonly responseText: string;
@@ -13186,13 +13186,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -13533,183 +13533,183 @@ interface NavigatorUserMedia {
}
interface NodeSelector {
querySelector(selectors: "a"): HTMLAnchorElement;
querySelector(selectors: "abbr"): HTMLElement;
querySelector(selectors: "acronym"): HTMLElement;
querySelector(selectors: "address"): HTMLElement;
querySelector(selectors: "applet"): HTMLAppletElement;
querySelector(selectors: "area"): HTMLAreaElement;
querySelector(selectors: "article"): HTMLElement;
querySelector(selectors: "aside"): HTMLElement;
querySelector(selectors: "audio"): HTMLAudioElement;
querySelector(selectors: "b"): HTMLElement;
querySelector(selectors: "base"): HTMLBaseElement;
querySelector(selectors: "basefont"): HTMLBaseFontElement;
querySelector(selectors: "bdo"): HTMLElement;
querySelector(selectors: "big"): HTMLElement;
querySelector(selectors: "blockquote"): HTMLQuoteElement;
querySelector(selectors: "body"): HTMLBodyElement;
querySelector(selectors: "br"): HTMLBRElement;
querySelector(selectors: "button"): HTMLButtonElement;
querySelector(selectors: "canvas"): HTMLCanvasElement;
querySelector(selectors: "caption"): HTMLTableCaptionElement;
querySelector(selectors: "center"): HTMLElement;
querySelector(selectors: "circle"): SVGCircleElement;
querySelector(selectors: "cite"): HTMLElement;
querySelector(selectors: "clippath"): SVGClipPathElement;
querySelector(selectors: "code"): HTMLElement;
querySelector(selectors: "col"): HTMLTableColElement;
querySelector(selectors: "colgroup"): HTMLTableColElement;
querySelector(selectors: "datalist"): HTMLDataListElement;
querySelector(selectors: "dd"): HTMLElement;
querySelector(selectors: "defs"): SVGDefsElement;
querySelector(selectors: "del"): HTMLModElement;
querySelector(selectors: "desc"): SVGDescElement;
querySelector(selectors: "dfn"): HTMLElement;
querySelector(selectors: "dir"): HTMLDirectoryElement;
querySelector(selectors: "div"): HTMLDivElement;
querySelector(selectors: "dl"): HTMLDListElement;
querySelector(selectors: "dt"): HTMLElement;
querySelector(selectors: "ellipse"): SVGEllipseElement;
querySelector(selectors: "em"): HTMLElement;
querySelector(selectors: "embed"): HTMLEmbedElement;
querySelector(selectors: "feblend"): SVGFEBlendElement;
querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement;
querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement;
querySelector(selectors: "fecomposite"): SVGFECompositeElement;
querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement;
querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement;
querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement;
querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement;
querySelector(selectors: "feflood"): SVGFEFloodElement;
querySelector(selectors: "fefunca"): SVGFEFuncAElement;
querySelector(selectors: "fefuncb"): SVGFEFuncBElement;
querySelector(selectors: "fefuncg"): SVGFEFuncGElement;
querySelector(selectors: "fefuncr"): SVGFEFuncRElement;
querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement;
querySelector(selectors: "feimage"): SVGFEImageElement;
querySelector(selectors: "femerge"): SVGFEMergeElement;
querySelector(selectors: "femergenode"): SVGFEMergeNodeElement;
querySelector(selectors: "femorphology"): SVGFEMorphologyElement;
querySelector(selectors: "feoffset"): SVGFEOffsetElement;
querySelector(selectors: "fepointlight"): SVGFEPointLightElement;
querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement;
querySelector(selectors: "fespotlight"): SVGFESpotLightElement;
querySelector(selectors: "fetile"): SVGFETileElement;
querySelector(selectors: "feturbulence"): SVGFETurbulenceElement;
querySelector(selectors: "fieldset"): HTMLFieldSetElement;
querySelector(selectors: "figcaption"): HTMLElement;
querySelector(selectors: "figure"): HTMLElement;
querySelector(selectors: "filter"): SVGFilterElement;
querySelector(selectors: "font"): HTMLFontElement;
querySelector(selectors: "footer"): HTMLElement;
querySelector(selectors: "foreignobject"): SVGForeignObjectElement;
querySelector(selectors: "form"): HTMLFormElement;
querySelector(selectors: "frame"): HTMLFrameElement;
querySelector(selectors: "frameset"): HTMLFrameSetElement;
querySelector(selectors: "g"): SVGGElement;
querySelector(selectors: "h1"): HTMLHeadingElement;
querySelector(selectors: "h2"): HTMLHeadingElement;
querySelector(selectors: "h3"): HTMLHeadingElement;
querySelector(selectors: "h4"): HTMLHeadingElement;
querySelector(selectors: "h5"): HTMLHeadingElement;
querySelector(selectors: "h6"): HTMLHeadingElement;
querySelector(selectors: "head"): HTMLHeadElement;
querySelector(selectors: "header"): HTMLElement;
querySelector(selectors: "hgroup"): HTMLElement;
querySelector(selectors: "hr"): HTMLHRElement;
querySelector(selectors: "html"): HTMLHtmlElement;
querySelector(selectors: "i"): HTMLElement;
querySelector(selectors: "iframe"): HTMLIFrameElement;
querySelector(selectors: "image"): SVGImageElement;
querySelector(selectors: "img"): HTMLImageElement;
querySelector(selectors: "input"): HTMLInputElement;
querySelector(selectors: "ins"): HTMLModElement;
querySelector(selectors: "isindex"): HTMLUnknownElement;
querySelector(selectors: "kbd"): HTMLElement;
querySelector(selectors: "keygen"): HTMLElement;
querySelector(selectors: "label"): HTMLLabelElement;
querySelector(selectors: "legend"): HTMLLegendElement;
querySelector(selectors: "li"): HTMLLIElement;
querySelector(selectors: "line"): SVGLineElement;
querySelector(selectors: "lineargradient"): SVGLinearGradientElement;
querySelector(selectors: "link"): HTMLLinkElement;
querySelector(selectors: "listing"): HTMLPreElement;
querySelector(selectors: "map"): HTMLMapElement;
querySelector(selectors: "mark"): HTMLElement;
querySelector(selectors: "marker"): SVGMarkerElement;
querySelector(selectors: "marquee"): HTMLMarqueeElement;
querySelector(selectors: "mask"): SVGMaskElement;
querySelector(selectors: "menu"): HTMLMenuElement;
querySelector(selectors: "meta"): HTMLMetaElement;
querySelector(selectors: "metadata"): SVGMetadataElement;
querySelector(selectors: "meter"): HTMLMeterElement;
querySelector(selectors: "nav"): HTMLElement;
querySelector(selectors: "nextid"): HTMLUnknownElement;
querySelector(selectors: "nobr"): HTMLElement;
querySelector(selectors: "noframes"): HTMLElement;
querySelector(selectors: "noscript"): HTMLElement;
querySelector(selectors: "object"): HTMLObjectElement;
querySelector(selectors: "ol"): HTMLOListElement;
querySelector(selectors: "optgroup"): HTMLOptGroupElement;
querySelector(selectors: "option"): HTMLOptionElement;
querySelector(selectors: "p"): HTMLParagraphElement;
querySelector(selectors: "param"): HTMLParamElement;
querySelector(selectors: "path"): SVGPathElement;
querySelector(selectors: "pattern"): SVGPatternElement;
querySelector(selectors: "picture"): HTMLPictureElement;
querySelector(selectors: "plaintext"): HTMLElement;
querySelector(selectors: "polygon"): SVGPolygonElement;
querySelector(selectors: "polyline"): SVGPolylineElement;
querySelector(selectors: "pre"): HTMLPreElement;
querySelector(selectors: "progress"): HTMLProgressElement;
querySelector(selectors: "q"): HTMLQuoteElement;
querySelector(selectors: "radialgradient"): SVGRadialGradientElement;
querySelector(selectors: "rect"): SVGRectElement;
querySelector(selectors: "rt"): HTMLElement;
querySelector(selectors: "ruby"): HTMLElement;
querySelector(selectors: "s"): HTMLElement;
querySelector(selectors: "samp"): HTMLElement;
querySelector(selectors: "script"): HTMLScriptElement;
querySelector(selectors: "section"): HTMLElement;
querySelector(selectors: "select"): HTMLSelectElement;
querySelector(selectors: "small"): HTMLElement;
querySelector(selectors: "source"): HTMLSourceElement;
querySelector(selectors: "span"): HTMLSpanElement;
querySelector(selectors: "stop"): SVGStopElement;
querySelector(selectors: "strike"): HTMLElement;
querySelector(selectors: "strong"): HTMLElement;
querySelector(selectors: "style"): HTMLStyleElement;
querySelector(selectors: "sub"): HTMLElement;
querySelector(selectors: "sup"): HTMLElement;
querySelector(selectors: "svg"): SVGSVGElement;
querySelector(selectors: "switch"): SVGSwitchElement;
querySelector(selectors: "symbol"): SVGSymbolElement;
querySelector(selectors: "table"): HTMLTableElement;
querySelector(selectors: "tbody"): HTMLTableSectionElement;
querySelector(selectors: "td"): HTMLTableDataCellElement;
querySelector(selectors: "template"): HTMLTemplateElement;
querySelector(selectors: "text"): SVGTextElement;
querySelector(selectors: "textpath"): SVGTextPathElement;
querySelector(selectors: "textarea"): HTMLTextAreaElement;
querySelector(selectors: "tfoot"): HTMLTableSectionElement;
querySelector(selectors: "th"): HTMLTableHeaderCellElement;
querySelector(selectors: "thead"): HTMLTableSectionElement;
querySelector(selectors: "title"): HTMLTitleElement;
querySelector(selectors: "tr"): HTMLTableRowElement;
querySelector(selectors: "track"): HTMLTrackElement;
querySelector(selectors: "tspan"): SVGTSpanElement;
querySelector(selectors: "tt"): HTMLElement;
querySelector(selectors: "u"): HTMLElement;
querySelector(selectors: "ul"): HTMLUListElement;
querySelector(selectors: "use"): SVGUseElement;
querySelector(selectors: "var"): HTMLElement;
querySelector(selectors: "video"): HTMLVideoElement;
querySelector(selectors: "view"): SVGViewElement;
querySelector(selectors: "wbr"): HTMLElement;
querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement;
querySelector(selectors: "xmp"): HTMLPreElement;
querySelector(selectors: string): Element;
querySelector(selectors: "a"): HTMLAnchorElement | null;
querySelector(selectors: "abbr"): HTMLElement | null;
querySelector(selectors: "acronym"): HTMLElement | null;
querySelector(selectors: "address"): HTMLElement | null;
querySelector(selectors: "applet"): HTMLAppletElement | null;
querySelector(selectors: "area"): HTMLAreaElement | null;
querySelector(selectors: "article"): HTMLElement | null;
querySelector(selectors: "aside"): HTMLElement | null;
querySelector(selectors: "audio"): HTMLAudioElement | null;
querySelector(selectors: "b"): HTMLElement | null;
querySelector(selectors: "base"): HTMLBaseElement | null;
querySelector(selectors: "basefont"): HTMLBaseFontElement | null;
querySelector(selectors: "bdo"): HTMLElement | null;
querySelector(selectors: "big"): HTMLElement | null;
querySelector(selectors: "blockquote"): HTMLQuoteElement | null;
querySelector(selectors: "body"): HTMLBodyElement | null;
querySelector(selectors: "br"): HTMLBRElement | null;
querySelector(selectors: "button"): HTMLButtonElement | null;
querySelector(selectors: "canvas"): HTMLCanvasElement | null;
querySelector(selectors: "caption"): HTMLTableCaptionElement | null;
querySelector(selectors: "center"): HTMLElement | null;
querySelector(selectors: "circle"): SVGCircleElement | null;
querySelector(selectors: "cite"): HTMLElement | null;
querySelector(selectors: "clippath"): SVGClipPathElement | null;
querySelector(selectors: "code"): HTMLElement | null;
querySelector(selectors: "col"): HTMLTableColElement | null;
querySelector(selectors: "colgroup"): HTMLTableColElement | null;
querySelector(selectors: "datalist"): HTMLDataListElement | null;
querySelector(selectors: "dd"): HTMLElement | null;
querySelector(selectors: "defs"): SVGDefsElement | null;
querySelector(selectors: "del"): HTMLModElement | null;
querySelector(selectors: "desc"): SVGDescElement | null;
querySelector(selectors: "dfn"): HTMLElement | null;
querySelector(selectors: "dir"): HTMLDirectoryElement | null;
querySelector(selectors: "div"): HTMLDivElement | null;
querySelector(selectors: "dl"): HTMLDListElement | null;
querySelector(selectors: "dt"): HTMLElement | null;
querySelector(selectors: "ellipse"): SVGEllipseElement | null;
querySelector(selectors: "em"): HTMLElement | null;
querySelector(selectors: "embed"): HTMLEmbedElement | null;
querySelector(selectors: "feblend"): SVGFEBlendElement | null;
querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement | null;
querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement | null;
querySelector(selectors: "fecomposite"): SVGFECompositeElement | null;
querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement | null;
querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement | null;
querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement | null;
querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement | null;
querySelector(selectors: "feflood"): SVGFEFloodElement | null;
querySelector(selectors: "fefunca"): SVGFEFuncAElement | null;
querySelector(selectors: "fefuncb"): SVGFEFuncBElement | null;
querySelector(selectors: "fefuncg"): SVGFEFuncGElement | null;
querySelector(selectors: "fefuncr"): SVGFEFuncRElement | null;
querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement | null;
querySelector(selectors: "feimage"): SVGFEImageElement | null;
querySelector(selectors: "femerge"): SVGFEMergeElement | null;
querySelector(selectors: "femergenode"): SVGFEMergeNodeElement | null;
querySelector(selectors: "femorphology"): SVGFEMorphologyElement | null;
querySelector(selectors: "feoffset"): SVGFEOffsetElement | null;
querySelector(selectors: "fepointlight"): SVGFEPointLightElement | null;
querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement | null;
querySelector(selectors: "fespotlight"): SVGFESpotLightElement | null;
querySelector(selectors: "fetile"): SVGFETileElement | null;
querySelector(selectors: "feturbulence"): SVGFETurbulenceElement | null;
querySelector(selectors: "fieldset"): HTMLFieldSetElement | null;
querySelector(selectors: "figcaption"): HTMLElement | null;
querySelector(selectors: "figure"): HTMLElement | null;
querySelector(selectors: "filter"): SVGFilterElement | null;
querySelector(selectors: "font"): HTMLFontElement | null;
querySelector(selectors: "footer"): HTMLElement | null;
querySelector(selectors: "foreignobject"): SVGForeignObjectElement | null;
querySelector(selectors: "form"): HTMLFormElement | null;
querySelector(selectors: "frame"): HTMLFrameElement | null;
querySelector(selectors: "frameset"): HTMLFrameSetElement | null;
querySelector(selectors: "g"): SVGGElement | null;
querySelector(selectors: "h1"): HTMLHeadingElement | null;
querySelector(selectors: "h2"): HTMLHeadingElement | null;
querySelector(selectors: "h3"): HTMLHeadingElement | null;
querySelector(selectors: "h4"): HTMLHeadingElement | null;
querySelector(selectors: "h5"): HTMLHeadingElement | null;
querySelector(selectors: "h6"): HTMLHeadingElement | null;
querySelector(selectors: "head"): HTMLHeadElement | null;
querySelector(selectors: "header"): HTMLElement | null;
querySelector(selectors: "hgroup"): HTMLElement | null;
querySelector(selectors: "hr"): HTMLHRElement | null;
querySelector(selectors: "html"): HTMLHtmlElement | null;
querySelector(selectors: "i"): HTMLElement | null;
querySelector(selectors: "iframe"): HTMLIFrameElement | null;
querySelector(selectors: "image"): SVGImageElement | null;
querySelector(selectors: "img"): HTMLImageElement | null;
querySelector(selectors: "input"): HTMLInputElement | null;
querySelector(selectors: "ins"): HTMLModElement | null;
querySelector(selectors: "isindex"): HTMLUnknownElement | null;
querySelector(selectors: "kbd"): HTMLElement | null;
querySelector(selectors: "keygen"): HTMLElement | null;
querySelector(selectors: "label"): HTMLLabelElement | null;
querySelector(selectors: "legend"): HTMLLegendElement | null;
querySelector(selectors: "li"): HTMLLIElement | null;
querySelector(selectors: "line"): SVGLineElement | null;
querySelector(selectors: "lineargradient"): SVGLinearGradientElement | null;
querySelector(selectors: "link"): HTMLLinkElement | null;
querySelector(selectors: "listing"): HTMLPreElement | null;
querySelector(selectors: "map"): HTMLMapElement | null;
querySelector(selectors: "mark"): HTMLElement | null;
querySelector(selectors: "marker"): SVGMarkerElement | null;
querySelector(selectors: "marquee"): HTMLMarqueeElement | null;
querySelector(selectors: "mask"): SVGMaskElement | null;
querySelector(selectors: "menu"): HTMLMenuElement | null;
querySelector(selectors: "meta"): HTMLMetaElement | null;
querySelector(selectors: "metadata"): SVGMetadataElement | null;
querySelector(selectors: "meter"): HTMLMeterElement | null;
querySelector(selectors: "nav"): HTMLElement | null;
querySelector(selectors: "nextid"): HTMLUnknownElement | null;
querySelector(selectors: "nobr"): HTMLElement | null;
querySelector(selectors: "noframes"): HTMLElement | null;
querySelector(selectors: "noscript"): HTMLElement | null;
querySelector(selectors: "object"): HTMLObjectElement | null;
querySelector(selectors: "ol"): HTMLOListElement | null;
querySelector(selectors: "optgroup"): HTMLOptGroupElement | null;
querySelector(selectors: "option"): HTMLOptionElement | null;
querySelector(selectors: "p"): HTMLParagraphElement | null;
querySelector(selectors: "param"): HTMLParamElement | null;
querySelector(selectors: "path"): SVGPathElement | null;
querySelector(selectors: "pattern"): SVGPatternElement | null;
querySelector(selectors: "picture"): HTMLPictureElement | null;
querySelector(selectors: "plaintext"): HTMLElement | null;
querySelector(selectors: "polygon"): SVGPolygonElement | null;
querySelector(selectors: "polyline"): SVGPolylineElement | null;
querySelector(selectors: "pre"): HTMLPreElement | null;
querySelector(selectors: "progress"): HTMLProgressElement | null;
querySelector(selectors: "q"): HTMLQuoteElement | null;
querySelector(selectors: "radialgradient"): SVGRadialGradientElement | null;
querySelector(selectors: "rect"): SVGRectElement | null;
querySelector(selectors: "rt"): HTMLElement | null;
querySelector(selectors: "ruby"): HTMLElement | null;
querySelector(selectors: "s"): HTMLElement | null;
querySelector(selectors: "samp"): HTMLElement | null;
querySelector(selectors: "script"): HTMLScriptElement | null;
querySelector(selectors: "section"): HTMLElement | null;
querySelector(selectors: "select"): HTMLSelectElement | null;
querySelector(selectors: "small"): HTMLElement | null;
querySelector(selectors: "source"): HTMLSourceElement | null;
querySelector(selectors: "span"): HTMLSpanElement | null;
querySelector(selectors: "stop"): SVGStopElement | null;
querySelector(selectors: "strike"): HTMLElement | null;
querySelector(selectors: "strong"): HTMLElement | null;
querySelector(selectors: "style"): HTMLStyleElement | null;
querySelector(selectors: "sub"): HTMLElement | null;
querySelector(selectors: "sup"): HTMLElement | null;
querySelector(selectors: "svg"): SVGSVGElement | null;
querySelector(selectors: "switch"): SVGSwitchElement | null;
querySelector(selectors: "symbol"): SVGSymbolElement | null;
querySelector(selectors: "table"): HTMLTableElement | null;
querySelector(selectors: "tbody"): HTMLTableSectionElement | null;
querySelector(selectors: "td"): HTMLTableDataCellElement | null;
querySelector(selectors: "template"): HTMLTemplateElement | null;
querySelector(selectors: "text"): SVGTextElement | null;
querySelector(selectors: "textpath"): SVGTextPathElement | null;
querySelector(selectors: "textarea"): HTMLTextAreaElement | null;
querySelector(selectors: "tfoot"): HTMLTableSectionElement | null;
querySelector(selectors: "th"): HTMLTableHeaderCellElement | null;
querySelector(selectors: "thead"): HTMLTableSectionElement | null;
querySelector(selectors: "title"): HTMLTitleElement | null;
querySelector(selectors: "tr"): HTMLTableRowElement | null;
querySelector(selectors: "track"): HTMLTrackElement | null;
querySelector(selectors: "tspan"): SVGTSpanElement | null;
querySelector(selectors: "tt"): HTMLElement | null;
querySelector(selectors: "u"): HTMLElement | null;
querySelector(selectors: "ul"): HTMLUListElement | null;
querySelector(selectors: "use"): SVGUseElement | null;
querySelector(selectors: "var"): HTMLElement | null;
querySelector(selectors: "video"): HTMLVideoElement | null;
querySelector(selectors: "view"): SVGViewElement | null;
querySelector(selectors: "wbr"): HTMLElement | null;
querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement | null;
querySelector(selectors: "xmp"): HTMLPreElement | null;
querySelector(selectors: string): Element | null;
querySelectorAll(selectors: "a"): NodeListOf<HTMLAnchorElement>;
querySelectorAll(selectors: "abbr"): NodeListOf<HTMLElement>;
querySelectorAll(selectors: "acronym"): NodeListOf<HTMLElement>;
@@ -14638,4 +14638,5 @@ type ScrollBehavior = "auto" | "instant" | "smooth";
type ScrollLogicalPosition = "start" | "center" | "end" | "nearest";
type IDBValidKey = number | string | Date | IDBArrayKey;
type BufferSource = ArrayBuffer | ArrayBufferView;
type MouseWheelEvent = WheelEvent;
type MouseWheelEvent = WheelEvent;
type ScrollRestoration = "auto" | "manual";
+1 -1
View File
@@ -217,7 +217,7 @@ interface NumberConstructor {
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
+27
View File
@@ -260,6 +260,9 @@ interface Function {
*/
bind(this: Function, thisArg: any, ...argArray: any[]): any;
/** Returns a string representation of a function. */
toString(): string;
prototype: any;
readonly length: number;
@@ -1216,6 +1219,30 @@ interface Array<T> {
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
+218 -190
View File
@@ -260,6 +260,9 @@ interface Function {
*/
bind(this: Function, thisArg: any, ...argArray: any[]): any;
/** Returns a string representation of a function. */
toString(): string;
prototype: any;
readonly length: number;
@@ -1216,6 +1219,30 @@ interface Array<T> {
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
@@ -4325,7 +4352,7 @@ interface NumberConstructor {
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
@@ -13361,11 +13388,12 @@ declare var HashChangeEvent: {
interface History {
readonly length: number;
readonly state: any;
back(distance?: any): void;
forward(distance?: any): void;
go(delta?: any): void;
pushState(statedata: any, title?: string, url?: string): void;
replaceState(statedata: any, title?: string, url?: string): void;
scrollRestoration: ScrollRestoration;
back(): void;
forward(): void;
go(delta?: number): void;
pushState(data: any, title: string, url?: string | null): void;
replaceState(data: any, title: string, url?: string | null): void;
}
declare var History: {
@@ -18937,7 +18965,6 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
[index: number]: Window;
}
declare var Window: {
@@ -18968,7 +18995,7 @@ declare var XMLDocument: {
}
interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
onreadystatechange: (this: this, ev: ProgressEvent) => any;
onreadystatechange: (this: this, ev: Event) => any;
readonly readyState: number;
readonly response: any;
readonly responseText: string;
@@ -18995,13 +19022,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -19342,183 +19369,183 @@ interface NavigatorUserMedia {
}
interface NodeSelector {
querySelector(selectors: "a"): HTMLAnchorElement;
querySelector(selectors: "abbr"): HTMLElement;
querySelector(selectors: "acronym"): HTMLElement;
querySelector(selectors: "address"): HTMLElement;
querySelector(selectors: "applet"): HTMLAppletElement;
querySelector(selectors: "area"): HTMLAreaElement;
querySelector(selectors: "article"): HTMLElement;
querySelector(selectors: "aside"): HTMLElement;
querySelector(selectors: "audio"): HTMLAudioElement;
querySelector(selectors: "b"): HTMLElement;
querySelector(selectors: "base"): HTMLBaseElement;
querySelector(selectors: "basefont"): HTMLBaseFontElement;
querySelector(selectors: "bdo"): HTMLElement;
querySelector(selectors: "big"): HTMLElement;
querySelector(selectors: "blockquote"): HTMLQuoteElement;
querySelector(selectors: "body"): HTMLBodyElement;
querySelector(selectors: "br"): HTMLBRElement;
querySelector(selectors: "button"): HTMLButtonElement;
querySelector(selectors: "canvas"): HTMLCanvasElement;
querySelector(selectors: "caption"): HTMLTableCaptionElement;
querySelector(selectors: "center"): HTMLElement;
querySelector(selectors: "circle"): SVGCircleElement;
querySelector(selectors: "cite"): HTMLElement;
querySelector(selectors: "clippath"): SVGClipPathElement;
querySelector(selectors: "code"): HTMLElement;
querySelector(selectors: "col"): HTMLTableColElement;
querySelector(selectors: "colgroup"): HTMLTableColElement;
querySelector(selectors: "datalist"): HTMLDataListElement;
querySelector(selectors: "dd"): HTMLElement;
querySelector(selectors: "defs"): SVGDefsElement;
querySelector(selectors: "del"): HTMLModElement;
querySelector(selectors: "desc"): SVGDescElement;
querySelector(selectors: "dfn"): HTMLElement;
querySelector(selectors: "dir"): HTMLDirectoryElement;
querySelector(selectors: "div"): HTMLDivElement;
querySelector(selectors: "dl"): HTMLDListElement;
querySelector(selectors: "dt"): HTMLElement;
querySelector(selectors: "ellipse"): SVGEllipseElement;
querySelector(selectors: "em"): HTMLElement;
querySelector(selectors: "embed"): HTMLEmbedElement;
querySelector(selectors: "feblend"): SVGFEBlendElement;
querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement;
querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement;
querySelector(selectors: "fecomposite"): SVGFECompositeElement;
querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement;
querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement;
querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement;
querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement;
querySelector(selectors: "feflood"): SVGFEFloodElement;
querySelector(selectors: "fefunca"): SVGFEFuncAElement;
querySelector(selectors: "fefuncb"): SVGFEFuncBElement;
querySelector(selectors: "fefuncg"): SVGFEFuncGElement;
querySelector(selectors: "fefuncr"): SVGFEFuncRElement;
querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement;
querySelector(selectors: "feimage"): SVGFEImageElement;
querySelector(selectors: "femerge"): SVGFEMergeElement;
querySelector(selectors: "femergenode"): SVGFEMergeNodeElement;
querySelector(selectors: "femorphology"): SVGFEMorphologyElement;
querySelector(selectors: "feoffset"): SVGFEOffsetElement;
querySelector(selectors: "fepointlight"): SVGFEPointLightElement;
querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement;
querySelector(selectors: "fespotlight"): SVGFESpotLightElement;
querySelector(selectors: "fetile"): SVGFETileElement;
querySelector(selectors: "feturbulence"): SVGFETurbulenceElement;
querySelector(selectors: "fieldset"): HTMLFieldSetElement;
querySelector(selectors: "figcaption"): HTMLElement;
querySelector(selectors: "figure"): HTMLElement;
querySelector(selectors: "filter"): SVGFilterElement;
querySelector(selectors: "font"): HTMLFontElement;
querySelector(selectors: "footer"): HTMLElement;
querySelector(selectors: "foreignobject"): SVGForeignObjectElement;
querySelector(selectors: "form"): HTMLFormElement;
querySelector(selectors: "frame"): HTMLFrameElement;
querySelector(selectors: "frameset"): HTMLFrameSetElement;
querySelector(selectors: "g"): SVGGElement;
querySelector(selectors: "h1"): HTMLHeadingElement;
querySelector(selectors: "h2"): HTMLHeadingElement;
querySelector(selectors: "h3"): HTMLHeadingElement;
querySelector(selectors: "h4"): HTMLHeadingElement;
querySelector(selectors: "h5"): HTMLHeadingElement;
querySelector(selectors: "h6"): HTMLHeadingElement;
querySelector(selectors: "head"): HTMLHeadElement;
querySelector(selectors: "header"): HTMLElement;
querySelector(selectors: "hgroup"): HTMLElement;
querySelector(selectors: "hr"): HTMLHRElement;
querySelector(selectors: "html"): HTMLHtmlElement;
querySelector(selectors: "i"): HTMLElement;
querySelector(selectors: "iframe"): HTMLIFrameElement;
querySelector(selectors: "image"): SVGImageElement;
querySelector(selectors: "img"): HTMLImageElement;
querySelector(selectors: "input"): HTMLInputElement;
querySelector(selectors: "ins"): HTMLModElement;
querySelector(selectors: "isindex"): HTMLUnknownElement;
querySelector(selectors: "kbd"): HTMLElement;
querySelector(selectors: "keygen"): HTMLElement;
querySelector(selectors: "label"): HTMLLabelElement;
querySelector(selectors: "legend"): HTMLLegendElement;
querySelector(selectors: "li"): HTMLLIElement;
querySelector(selectors: "line"): SVGLineElement;
querySelector(selectors: "lineargradient"): SVGLinearGradientElement;
querySelector(selectors: "link"): HTMLLinkElement;
querySelector(selectors: "listing"): HTMLPreElement;
querySelector(selectors: "map"): HTMLMapElement;
querySelector(selectors: "mark"): HTMLElement;
querySelector(selectors: "marker"): SVGMarkerElement;
querySelector(selectors: "marquee"): HTMLMarqueeElement;
querySelector(selectors: "mask"): SVGMaskElement;
querySelector(selectors: "menu"): HTMLMenuElement;
querySelector(selectors: "meta"): HTMLMetaElement;
querySelector(selectors: "metadata"): SVGMetadataElement;
querySelector(selectors: "meter"): HTMLMeterElement;
querySelector(selectors: "nav"): HTMLElement;
querySelector(selectors: "nextid"): HTMLUnknownElement;
querySelector(selectors: "nobr"): HTMLElement;
querySelector(selectors: "noframes"): HTMLElement;
querySelector(selectors: "noscript"): HTMLElement;
querySelector(selectors: "object"): HTMLObjectElement;
querySelector(selectors: "ol"): HTMLOListElement;
querySelector(selectors: "optgroup"): HTMLOptGroupElement;
querySelector(selectors: "option"): HTMLOptionElement;
querySelector(selectors: "p"): HTMLParagraphElement;
querySelector(selectors: "param"): HTMLParamElement;
querySelector(selectors: "path"): SVGPathElement;
querySelector(selectors: "pattern"): SVGPatternElement;
querySelector(selectors: "picture"): HTMLPictureElement;
querySelector(selectors: "plaintext"): HTMLElement;
querySelector(selectors: "polygon"): SVGPolygonElement;
querySelector(selectors: "polyline"): SVGPolylineElement;
querySelector(selectors: "pre"): HTMLPreElement;
querySelector(selectors: "progress"): HTMLProgressElement;
querySelector(selectors: "q"): HTMLQuoteElement;
querySelector(selectors: "radialgradient"): SVGRadialGradientElement;
querySelector(selectors: "rect"): SVGRectElement;
querySelector(selectors: "rt"): HTMLElement;
querySelector(selectors: "ruby"): HTMLElement;
querySelector(selectors: "s"): HTMLElement;
querySelector(selectors: "samp"): HTMLElement;
querySelector(selectors: "script"): HTMLScriptElement;
querySelector(selectors: "section"): HTMLElement;
querySelector(selectors: "select"): HTMLSelectElement;
querySelector(selectors: "small"): HTMLElement;
querySelector(selectors: "source"): HTMLSourceElement;
querySelector(selectors: "span"): HTMLSpanElement;
querySelector(selectors: "stop"): SVGStopElement;
querySelector(selectors: "strike"): HTMLElement;
querySelector(selectors: "strong"): HTMLElement;
querySelector(selectors: "style"): HTMLStyleElement;
querySelector(selectors: "sub"): HTMLElement;
querySelector(selectors: "sup"): HTMLElement;
querySelector(selectors: "svg"): SVGSVGElement;
querySelector(selectors: "switch"): SVGSwitchElement;
querySelector(selectors: "symbol"): SVGSymbolElement;
querySelector(selectors: "table"): HTMLTableElement;
querySelector(selectors: "tbody"): HTMLTableSectionElement;
querySelector(selectors: "td"): HTMLTableDataCellElement;
querySelector(selectors: "template"): HTMLTemplateElement;
querySelector(selectors: "text"): SVGTextElement;
querySelector(selectors: "textpath"): SVGTextPathElement;
querySelector(selectors: "textarea"): HTMLTextAreaElement;
querySelector(selectors: "tfoot"): HTMLTableSectionElement;
querySelector(selectors: "th"): HTMLTableHeaderCellElement;
querySelector(selectors: "thead"): HTMLTableSectionElement;
querySelector(selectors: "title"): HTMLTitleElement;
querySelector(selectors: "tr"): HTMLTableRowElement;
querySelector(selectors: "track"): HTMLTrackElement;
querySelector(selectors: "tspan"): SVGTSpanElement;
querySelector(selectors: "tt"): HTMLElement;
querySelector(selectors: "u"): HTMLElement;
querySelector(selectors: "ul"): HTMLUListElement;
querySelector(selectors: "use"): SVGUseElement;
querySelector(selectors: "var"): HTMLElement;
querySelector(selectors: "video"): HTMLVideoElement;
querySelector(selectors: "view"): SVGViewElement;
querySelector(selectors: "wbr"): HTMLElement;
querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement;
querySelector(selectors: "xmp"): HTMLPreElement;
querySelector(selectors: string): Element;
querySelector(selectors: "a"): HTMLAnchorElement | null;
querySelector(selectors: "abbr"): HTMLElement | null;
querySelector(selectors: "acronym"): HTMLElement | null;
querySelector(selectors: "address"): HTMLElement | null;
querySelector(selectors: "applet"): HTMLAppletElement | null;
querySelector(selectors: "area"): HTMLAreaElement | null;
querySelector(selectors: "article"): HTMLElement | null;
querySelector(selectors: "aside"): HTMLElement | null;
querySelector(selectors: "audio"): HTMLAudioElement | null;
querySelector(selectors: "b"): HTMLElement | null;
querySelector(selectors: "base"): HTMLBaseElement | null;
querySelector(selectors: "basefont"): HTMLBaseFontElement | null;
querySelector(selectors: "bdo"): HTMLElement | null;
querySelector(selectors: "big"): HTMLElement | null;
querySelector(selectors: "blockquote"): HTMLQuoteElement | null;
querySelector(selectors: "body"): HTMLBodyElement | null;
querySelector(selectors: "br"): HTMLBRElement | null;
querySelector(selectors: "button"): HTMLButtonElement | null;
querySelector(selectors: "canvas"): HTMLCanvasElement | null;
querySelector(selectors: "caption"): HTMLTableCaptionElement | null;
querySelector(selectors: "center"): HTMLElement | null;
querySelector(selectors: "circle"): SVGCircleElement | null;
querySelector(selectors: "cite"): HTMLElement | null;
querySelector(selectors: "clippath"): SVGClipPathElement | null;
querySelector(selectors: "code"): HTMLElement | null;
querySelector(selectors: "col"): HTMLTableColElement | null;
querySelector(selectors: "colgroup"): HTMLTableColElement | null;
querySelector(selectors: "datalist"): HTMLDataListElement | null;
querySelector(selectors: "dd"): HTMLElement | null;
querySelector(selectors: "defs"): SVGDefsElement | null;
querySelector(selectors: "del"): HTMLModElement | null;
querySelector(selectors: "desc"): SVGDescElement | null;
querySelector(selectors: "dfn"): HTMLElement | null;
querySelector(selectors: "dir"): HTMLDirectoryElement | null;
querySelector(selectors: "div"): HTMLDivElement | null;
querySelector(selectors: "dl"): HTMLDListElement | null;
querySelector(selectors: "dt"): HTMLElement | null;
querySelector(selectors: "ellipse"): SVGEllipseElement | null;
querySelector(selectors: "em"): HTMLElement | null;
querySelector(selectors: "embed"): HTMLEmbedElement | null;
querySelector(selectors: "feblend"): SVGFEBlendElement | null;
querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement | null;
querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement | null;
querySelector(selectors: "fecomposite"): SVGFECompositeElement | null;
querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement | null;
querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement | null;
querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement | null;
querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement | null;
querySelector(selectors: "feflood"): SVGFEFloodElement | null;
querySelector(selectors: "fefunca"): SVGFEFuncAElement | null;
querySelector(selectors: "fefuncb"): SVGFEFuncBElement | null;
querySelector(selectors: "fefuncg"): SVGFEFuncGElement | null;
querySelector(selectors: "fefuncr"): SVGFEFuncRElement | null;
querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement | null;
querySelector(selectors: "feimage"): SVGFEImageElement | null;
querySelector(selectors: "femerge"): SVGFEMergeElement | null;
querySelector(selectors: "femergenode"): SVGFEMergeNodeElement | null;
querySelector(selectors: "femorphology"): SVGFEMorphologyElement | null;
querySelector(selectors: "feoffset"): SVGFEOffsetElement | null;
querySelector(selectors: "fepointlight"): SVGFEPointLightElement | null;
querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement | null;
querySelector(selectors: "fespotlight"): SVGFESpotLightElement | null;
querySelector(selectors: "fetile"): SVGFETileElement | null;
querySelector(selectors: "feturbulence"): SVGFETurbulenceElement | null;
querySelector(selectors: "fieldset"): HTMLFieldSetElement | null;
querySelector(selectors: "figcaption"): HTMLElement | null;
querySelector(selectors: "figure"): HTMLElement | null;
querySelector(selectors: "filter"): SVGFilterElement | null;
querySelector(selectors: "font"): HTMLFontElement | null;
querySelector(selectors: "footer"): HTMLElement | null;
querySelector(selectors: "foreignobject"): SVGForeignObjectElement | null;
querySelector(selectors: "form"): HTMLFormElement | null;
querySelector(selectors: "frame"): HTMLFrameElement | null;
querySelector(selectors: "frameset"): HTMLFrameSetElement | null;
querySelector(selectors: "g"): SVGGElement | null;
querySelector(selectors: "h1"): HTMLHeadingElement | null;
querySelector(selectors: "h2"): HTMLHeadingElement | null;
querySelector(selectors: "h3"): HTMLHeadingElement | null;
querySelector(selectors: "h4"): HTMLHeadingElement | null;
querySelector(selectors: "h5"): HTMLHeadingElement | null;
querySelector(selectors: "h6"): HTMLHeadingElement | null;
querySelector(selectors: "head"): HTMLHeadElement | null;
querySelector(selectors: "header"): HTMLElement | null;
querySelector(selectors: "hgroup"): HTMLElement | null;
querySelector(selectors: "hr"): HTMLHRElement | null;
querySelector(selectors: "html"): HTMLHtmlElement | null;
querySelector(selectors: "i"): HTMLElement | null;
querySelector(selectors: "iframe"): HTMLIFrameElement | null;
querySelector(selectors: "image"): SVGImageElement | null;
querySelector(selectors: "img"): HTMLImageElement | null;
querySelector(selectors: "input"): HTMLInputElement | null;
querySelector(selectors: "ins"): HTMLModElement | null;
querySelector(selectors: "isindex"): HTMLUnknownElement | null;
querySelector(selectors: "kbd"): HTMLElement | null;
querySelector(selectors: "keygen"): HTMLElement | null;
querySelector(selectors: "label"): HTMLLabelElement | null;
querySelector(selectors: "legend"): HTMLLegendElement | null;
querySelector(selectors: "li"): HTMLLIElement | null;
querySelector(selectors: "line"): SVGLineElement | null;
querySelector(selectors: "lineargradient"): SVGLinearGradientElement | null;
querySelector(selectors: "link"): HTMLLinkElement | null;
querySelector(selectors: "listing"): HTMLPreElement | null;
querySelector(selectors: "map"): HTMLMapElement | null;
querySelector(selectors: "mark"): HTMLElement | null;
querySelector(selectors: "marker"): SVGMarkerElement | null;
querySelector(selectors: "marquee"): HTMLMarqueeElement | null;
querySelector(selectors: "mask"): SVGMaskElement | null;
querySelector(selectors: "menu"): HTMLMenuElement | null;
querySelector(selectors: "meta"): HTMLMetaElement | null;
querySelector(selectors: "metadata"): SVGMetadataElement | null;
querySelector(selectors: "meter"): HTMLMeterElement | null;
querySelector(selectors: "nav"): HTMLElement | null;
querySelector(selectors: "nextid"): HTMLUnknownElement | null;
querySelector(selectors: "nobr"): HTMLElement | null;
querySelector(selectors: "noframes"): HTMLElement | null;
querySelector(selectors: "noscript"): HTMLElement | null;
querySelector(selectors: "object"): HTMLObjectElement | null;
querySelector(selectors: "ol"): HTMLOListElement | null;
querySelector(selectors: "optgroup"): HTMLOptGroupElement | null;
querySelector(selectors: "option"): HTMLOptionElement | null;
querySelector(selectors: "p"): HTMLParagraphElement | null;
querySelector(selectors: "param"): HTMLParamElement | null;
querySelector(selectors: "path"): SVGPathElement | null;
querySelector(selectors: "pattern"): SVGPatternElement | null;
querySelector(selectors: "picture"): HTMLPictureElement | null;
querySelector(selectors: "plaintext"): HTMLElement | null;
querySelector(selectors: "polygon"): SVGPolygonElement | null;
querySelector(selectors: "polyline"): SVGPolylineElement | null;
querySelector(selectors: "pre"): HTMLPreElement | null;
querySelector(selectors: "progress"): HTMLProgressElement | null;
querySelector(selectors: "q"): HTMLQuoteElement | null;
querySelector(selectors: "radialgradient"): SVGRadialGradientElement | null;
querySelector(selectors: "rect"): SVGRectElement | null;
querySelector(selectors: "rt"): HTMLElement | null;
querySelector(selectors: "ruby"): HTMLElement | null;
querySelector(selectors: "s"): HTMLElement | null;
querySelector(selectors: "samp"): HTMLElement | null;
querySelector(selectors: "script"): HTMLScriptElement | null;
querySelector(selectors: "section"): HTMLElement | null;
querySelector(selectors: "select"): HTMLSelectElement | null;
querySelector(selectors: "small"): HTMLElement | null;
querySelector(selectors: "source"): HTMLSourceElement | null;
querySelector(selectors: "span"): HTMLSpanElement | null;
querySelector(selectors: "stop"): SVGStopElement | null;
querySelector(selectors: "strike"): HTMLElement | null;
querySelector(selectors: "strong"): HTMLElement | null;
querySelector(selectors: "style"): HTMLStyleElement | null;
querySelector(selectors: "sub"): HTMLElement | null;
querySelector(selectors: "sup"): HTMLElement | null;
querySelector(selectors: "svg"): SVGSVGElement | null;
querySelector(selectors: "switch"): SVGSwitchElement | null;
querySelector(selectors: "symbol"): SVGSymbolElement | null;
querySelector(selectors: "table"): HTMLTableElement | null;
querySelector(selectors: "tbody"): HTMLTableSectionElement | null;
querySelector(selectors: "td"): HTMLTableDataCellElement | null;
querySelector(selectors: "template"): HTMLTemplateElement | null;
querySelector(selectors: "text"): SVGTextElement | null;
querySelector(selectors: "textpath"): SVGTextPathElement | null;
querySelector(selectors: "textarea"): HTMLTextAreaElement | null;
querySelector(selectors: "tfoot"): HTMLTableSectionElement | null;
querySelector(selectors: "th"): HTMLTableHeaderCellElement | null;
querySelector(selectors: "thead"): HTMLTableSectionElement | null;
querySelector(selectors: "title"): HTMLTitleElement | null;
querySelector(selectors: "tr"): HTMLTableRowElement | null;
querySelector(selectors: "track"): HTMLTrackElement | null;
querySelector(selectors: "tspan"): SVGTSpanElement | null;
querySelector(selectors: "tt"): HTMLElement | null;
querySelector(selectors: "u"): HTMLElement | null;
querySelector(selectors: "ul"): HTMLUListElement | null;
querySelector(selectors: "use"): SVGUseElement | null;
querySelector(selectors: "var"): HTMLElement | null;
querySelector(selectors: "video"): HTMLVideoElement | null;
querySelector(selectors: "view"): SVGViewElement | null;
querySelector(selectors: "wbr"): HTMLElement | null;
querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement | null;
querySelector(selectors: "xmp"): HTMLPreElement | null;
querySelector(selectors: string): Element | null;
querySelectorAll(selectors: "a"): NodeListOf<HTMLAnchorElement>;
querySelectorAll(selectors: "abbr"): NodeListOf<HTMLElement>;
querySelectorAll(selectors: "acronym"): NodeListOf<HTMLElement>;
@@ -20448,6 +20475,7 @@ type ScrollLogicalPosition = "start" | "center" | "end" | "nearest";
type IDBValidKey = number | string | Date | IDBArrayKey;
type BufferSource = ArrayBuffer | ArrayBufferView;
type MouseWheelEvent = WheelEvent;
type ScrollRestoration = "auto" | "manual";
/////////////////////////////
/// WorkerGlobalScope APIs
/////////////////////////////
+6 -6
View File
@@ -744,7 +744,7 @@ declare var Worker: {
}
interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
onreadystatechange: (this: this, ev: ProgressEvent) => any;
onreadystatechange: (this: this, ev: Event) => any;
readonly readyState: number;
readonly response: any;
readonly responseText: string;
@@ -770,13 +770,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
+1848
View File
File diff suppressed because it is too large Load Diff
+1935 -1642
View File
File diff suppressed because it is too large Load Diff
+6230 -3896
View File
File diff suppressed because it is too large Load Diff
+1851 -505
View File
File diff suppressed because one or more lines are too long
+6082 -3879
View File
File diff suppressed because it is too large Load Diff
+381 -99
View File
File diff suppressed because it is too large Load Diff
+2806 -2123
View File
File diff suppressed because it is too large Load Diff
+381 -99
View File
File diff suppressed because it is too large Load Diff
+2806 -2123
View File
File diff suppressed because it is too large Load Diff
+257 -120
View File
@@ -72,7 +72,6 @@ var ts;
(function (ts) {
ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); };
})(ts || (ts = {}));
var ts;
(function (ts) {
var performance;
(function (performance) {
@@ -790,6 +789,56 @@ var ts;
};
}
ts.memoize = memoize;
function chain(a, b, c, d, e) {
if (e) {
var args_2 = [];
for (var i = 0; i < arguments.length; i++) {
args_2[i] = arguments[i];
}
return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); };
}
else if (d) {
return function (t) { return compose(a(t), b(t), c(t), d(t)); };
}
else if (c) {
return function (t) { return compose(a(t), b(t), c(t)); };
}
else if (b) {
return function (t) { return compose(a(t), b(t)); };
}
else if (a) {
return function (t) { return compose(a(t)); };
}
else {
return function (t) { return function (u) { return u; }; };
}
}
ts.chain = chain;
function compose(a, b, c, d, e) {
if (e) {
var args_3 = [];
for (var i = 0; i < arguments.length; i++) {
args_3[i] = arguments[i];
}
return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); };
}
else if (d) {
return function (t) { return d(c(b(a(t)))); };
}
else if (c) {
return function (t) { return c(b(a(t))); };
}
else if (b) {
return function (t) { return b(a(t)); };
}
else if (a) {
return function (t) { return a(t); };
}
else {
return function (t) { return t; };
}
}
ts.compose = compose;
function formatStringFromArgs(text, args, baseIndex) {
baseIndex = baseIndex || 0;
return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; });
@@ -1537,7 +1586,6 @@ var ts;
this.transformFlags = 0;
this.parent = undefined;
this.original = undefined;
this.transformId = 0;
}
ts.objectAllocator = {
getNodeConstructor: function () { return Node; },
@@ -1550,9 +1598,9 @@ var ts;
};
var Debug;
(function (Debug) {
var currentAssertionLevel;
Debug.currentAssertionLevel = 0;
function shouldAssert(level) {
return getCurrentAssertionLevel() >= level;
return Debug.currentAssertionLevel >= level;
}
Debug.shouldAssert = shouldAssert;
function assert(expression, message, verboseDebugInfo) {
@@ -1570,30 +1618,7 @@ var ts;
Debug.assert(false, message);
}
Debug.fail = fail;
function getCurrentAssertionLevel() {
if (currentAssertionLevel !== undefined) {
return currentAssertionLevel;
}
if (ts.sys === undefined) {
return 0;
}
var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV"));
currentAssertionLevel = developmentMode
? 1
: 0;
return currentAssertionLevel;
}
})(Debug = ts.Debug || (ts.Debug = {}));
function getEnvironmentVariable(name, host) {
if (host && host.getEnvironmentVariable) {
return host.getEnvironmentVariable(name);
}
if (ts.sys && ts.sys.getEnvironmentVariable) {
return ts.sys.getEnvironmentVariable(name);
}
return "";
}
ts.getEnvironmentVariable = getEnvironmentVariable;
function orderedRemoveItemAt(array, index) {
for (var i = index; i < array.length - 1; i++) {
array[i] = array[i + 1];
@@ -1624,6 +1649,60 @@ var ts;
: (function (fileName) { return fileName.toLowerCase(); });
}
ts.createGetCanonicalFileName = createGetCanonicalFileName;
function matchPatternOrExact(patternStrings, candidate) {
var patterns = [];
for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
var patternString = patternStrings_1[_i];
var pattern = tryParsePattern(patternString);
if (pattern) {
patterns.push(pattern);
}
else if (patternString === candidate) {
return patternString;
}
}
return findBestPatternMatch(patterns, function (_) { return _; }, candidate);
}
ts.matchPatternOrExact = matchPatternOrExact;
function patternText(_a) {
var prefix = _a.prefix, suffix = _a.suffix;
return prefix + "*" + suffix;
}
ts.patternText = patternText;
function matchedText(pattern, candidate) {
Debug.assert(isPatternMatch(pattern, candidate));
return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length);
}
ts.matchedText = matchedText;
function findBestPatternMatch(values, getPattern, candidate) {
var matchedValue = undefined;
var longestMatchPrefixLength = -1;
for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
var v = values_1[_i];
var pattern = getPattern(v);
if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
longestMatchPrefixLength = pattern.prefix.length;
matchedValue = v;
}
}
return matchedValue;
}
ts.findBestPatternMatch = findBestPatternMatch;
function isPatternMatch(_a, candidate) {
var prefix = _a.prefix, suffix = _a.suffix;
return candidate.length >= prefix.length + suffix.length &&
startsWith(candidate, prefix) &&
endsWith(candidate, suffix);
}
function tryParsePattern(pattern) {
Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
var indexOfStar = pattern.indexOf("*");
return indexOfStar === -1 ? undefined : {
prefix: pattern.substr(0, indexOfStar),
suffix: pattern.substr(indexOfStar + 1)
};
}
ts.tryParsePattern = tryParsePattern;
function positionIsSynthesized(pos) {
return !(pos >= 0);
}
@@ -1821,8 +1900,14 @@ var ts;
function isNode4OrLater() {
return parseInt(process.version.charAt(1)) >= 4;
}
function isFileSystemCaseSensitive() {
if (platform === "win32" || platform === "win64") {
return false;
}
return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase());
}
var platform = _os.platform();
var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin";
var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
function readFile(fileName, encoding) {
if (!fileExists(fileName)) {
return undefined;
@@ -1947,6 +2032,9 @@ var ts;
},
watchDirectory: function (directoryName, callback, recursive) {
var options;
if (!directoryExists(directoryName)) {
return;
}
if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) {
options = { persistent: true, recursive: !!recursive };
}
@@ -2090,6 +2178,11 @@ var ts;
}
return sys;
})();
if (ts.sys && ts.sys.getEnvironmentVariable) {
ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
? 1
: 0;
}
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -2414,7 +2507,7 @@ var ts;
The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." },
Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." },
Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" },
All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." },
The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." },
Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." },
Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." },
Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." },
@@ -2575,7 +2668,7 @@ var ts;
this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." },
The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." },
The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." },
Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" },
_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." },
All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." },
Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." },
Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" },
@@ -2809,6 +2902,7 @@ var ts;
Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." },
Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." },
Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." },
Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." },
@@ -2833,6 +2927,7 @@ var ts;
Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." },
Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." },
Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." },
Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined." },
You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." },
You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." },
import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." },
@@ -2862,7 +2957,14 @@ var ts;
super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." },
Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." },
Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" },
The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." }
The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." },
Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." },
Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." },
Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" },
Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" },
Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" },
Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" },
Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" }
};
})(ts || (ts = {}));
var ts;
@@ -3772,7 +3874,7 @@ var ts;
return token = 69;
}
function scanBinaryOrOctalDigits(base) {
ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8");
ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8");
var value = 0;
var numberOfDigits = 0;
while (true) {
@@ -4844,6 +4946,11 @@ var ts;
name: "importHelpers",
type: "boolean",
description: ts.Diagnostics.Import_emit_helpers_from_tslib
},
{
name: "alwaysStrict",
type: "boolean",
description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
}
];
ts.typingOptionDeclarations = [
@@ -5294,7 +5401,7 @@ var ts;
ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson;
function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
var options = ts.getBaseFileName(configFileName) === "jsconfig.json"
? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true }
? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true }
: {};
convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors);
return options;
@@ -5704,7 +5811,7 @@ var ts;
else if (host.getCurrentDirectory) {
currentDirectory = host.getCurrentDirectory();
}
return currentDirectory && getDefaultTypeRoots(currentDirectory, host);
return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host);
}
ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
function getDefaultTypeRoots(currentDirectory, host) {
@@ -5958,11 +6065,11 @@ var ts;
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
}
matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName);
matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName);
}
if (matchedPattern) {
var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName);
var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern);
var matchedStar = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName);
var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern);
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
}
@@ -5988,57 +6095,6 @@ var ts;
return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
}
}
function matchPatternOrExact(patternStrings, candidate) {
var patterns = [];
for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
var patternString = patternStrings_1[_i];
var pattern = tryParsePattern(patternString);
if (pattern) {
patterns.push(pattern);
}
else if (patternString === candidate) {
return patternString;
}
}
return findBestPatternMatch(patterns, function (_) { return _; }, candidate);
}
function patternText(_a) {
var prefix = _a.prefix, suffix = _a.suffix;
return prefix + "*" + suffix;
}
function matchedText(pattern, candidate) {
ts.Debug.assert(isPatternMatch(pattern, candidate));
return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length);
}
function findBestPatternMatch(values, getPattern, candidate) {
var matchedValue = undefined;
var longestMatchPrefixLength = -1;
for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
var v = values_1[_i];
var pattern = getPattern(v);
if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
longestMatchPrefixLength = pattern.prefix.length;
matchedValue = v;
}
}
return matchedValue;
}
ts.findBestPatternMatch = findBestPatternMatch;
function isPatternMatch(_a, candidate) {
var prefix = _a.prefix, suffix = _a.suffix;
return candidate.length >= prefix.length + suffix.length &&
ts.startsWith(candidate, prefix) &&
ts.endsWith(candidate, suffix);
}
function tryParsePattern(pattern) {
ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern));
var indexOfStar = pattern.indexOf("*");
return indexOfStar === -1 ? undefined : {
prefix: pattern.substr(0, indexOfStar),
suffix: pattern.substr(indexOfStar + 1)
};
}
ts.tryParsePattern = tryParsePattern;
function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) {
var containingDirectory = ts.getDirectoryPath(containingFile);
var supportedExtensions = ts.getSupportedExtensions(compilerOptions);
@@ -6169,20 +6225,28 @@ var ts;
}
}
function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) {
return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, false);
}
ts.loadModuleFromNodeModules = loadModuleFromNodeModules;
function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) {
return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, false, true);
}
function loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, typesOnly) {
directory = ts.normalizeSlashes(directory);
while (true) {
var baseName = ts.getBaseFileName(directory);
if (baseName !== "node_modules") {
var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) {
return packageResult;
}
else {
var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state);
if (typesResult || packageResult) {
return typesResult || packageResult;
var packageResult = void 0;
if (!typesOnly) {
packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state);
if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) {
return packageResult;
}
}
var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state);
if (typesResult || packageResult) {
return typesResult || packageResult;
}
}
var parentPath = ts.getDirectoryPath(directory);
if (parentPath === directory || checkOneLevel) {
@@ -6192,7 +6256,6 @@ var ts;
}
return undefined;
}
ts.loadModuleFromNodeModules = loadModuleFromNodeModules;
function classicNameResolver(moduleName, containingFile, compilerOptions, host) {
var traceEnabled = isTraceEnabled(compilerOptions, host);
var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx };
@@ -6205,18 +6268,8 @@ var ts;
}
var referencedSourceFile;
if (moduleHasNonRelativeName(moduleName)) {
while (true) {
var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state);
if (referencedSourceFile) {
break;
}
var parentPath = ts.getDirectoryPath(containingDirectory);
if (parentPath === containingDirectory) {
break;
}
containingDirectory = parentPath;
}
referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) ||
loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state);
}
else {
var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
@@ -6227,6 +6280,20 @@ var ts;
: { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
}
ts.classicNameResolver = classicNameResolver;
function loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) {
while (true) {
var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
var referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state);
if (referencedSourceFile) {
return referencedSourceFile;
}
var parentPath = ts.getDirectoryPath(containingDirectory);
if (parentPath === containingDirectory) {
return undefined;
}
containingDirectory = parentPath;
}
}
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -6242,6 +6309,36 @@ var ts;
var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost);
return result.resolvedModule && result.resolvedModule.resolvedFileName;
}
(function (PackageNameValidationResult) {
PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok";
PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported";
PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 2] = "NameTooLong";
PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot";
PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
})(typingsInstaller.PackageNameValidationResult || (typingsInstaller.PackageNameValidationResult = {}));
var PackageNameValidationResult = typingsInstaller.PackageNameValidationResult;
typingsInstaller.MaxPackageNameLength = 214;
function validatePackageName(packageName) {
ts.Debug.assert(!!packageName, "Package name is not specified");
if (packageName.length > typingsInstaller.MaxPackageNameLength) {
return PackageNameValidationResult.NameTooLong;
}
if (packageName.charCodeAt(0) === 46) {
return PackageNameValidationResult.NameStartsWithDot;
}
if (packageName.charCodeAt(0) === 95) {
return PackageNameValidationResult.NameStartsWithUnderscore;
}
if (/^@[^/]+\/[^/]+$/.test(packageName)) {
return PackageNameValidationResult.ScopedPackagesNotSupported;
}
if (encodeURIComponent(packageName) !== packageName) {
return PackageNameValidationResult.NameContainsNonURISafeCharacters;
}
return PackageNameValidationResult.Ok;
}
typingsInstaller.validatePackageName = validatePackageName;
typingsInstaller.NpmViewRequest = "npm view";
typingsInstaller.NpmInstallRequest = "npm install";
var TypingsInstaller = (function () {
@@ -6364,15 +6461,54 @@ var ts;
}
this.knownCachesSet[cacheLocation] = true;
};
TypingsInstaller.prototype.filterTypings = function (typingsToInstall) {
if (typingsToInstall.length === 0) {
return typingsToInstall;
}
var result = [];
for (var _i = 0, typingsToInstall_1 = typingsToInstall; _i < typingsToInstall_1.length; _i++) {
var typing = typingsToInstall_1[_i];
if (this.missingTypingsSet[typing]) {
continue;
}
var validationResult = validatePackageName(typing);
if (validationResult === PackageNameValidationResult.Ok) {
result.push(typing);
}
else {
this.missingTypingsSet[typing] = true;
if (this.log.isEnabled()) {
switch (validationResult) {
case PackageNameValidationResult.NameTooLong:
this.log.writeLine("Package name '" + typing + "' should be less than " + typingsInstaller.MaxPackageNameLength + " characters");
break;
case PackageNameValidationResult.NameStartsWithDot:
this.log.writeLine("Package name '" + typing + "' cannot start with '.'");
break;
case PackageNameValidationResult.NameStartsWithUnderscore:
this.log.writeLine("Package name '" + typing + "' cannot start with '_'");
break;
case PackageNameValidationResult.ScopedPackagesNotSupported:
this.log.writeLine("Package '" + typing + "' is scoped and currently is not supported");
break;
case PackageNameValidationResult.NameContainsNonURISafeCharacters:
this.log.writeLine("Package name '" + typing + "' contains non URI safe characters");
break;
}
}
}
}
return result;
};
TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) {
var _this = this;
if (this.log.isEnabled()) {
this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall));
}
typingsToInstall = ts.filter(typingsToInstall, function (x) { return !_this.missingTypingsSet[x]; });
typingsToInstall = this.filterTypings(typingsToInstall);
if (typingsToInstall.length === 0) {
if (this.log.isEnabled()) {
this.log.writeLine("All typings are known to be missing - no need to go any further");
this.log.writeLine("All typings are known to be missing or invalid - no need to go any further");
}
return;
}
@@ -6412,8 +6548,8 @@ var ts;
if (_this.log.isEnabled()) {
_this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles));
}
for (var _a = 0, typingsToInstall_1 = typingsToInstall; _a < typingsToInstall_1.length; _a++) {
var toInstall = typingsToInstall_1[_a];
for (var _a = 0, typingsToInstall_2 = typingsToInstall; _a < typingsToInstall_2.length; _a++) {
var toInstall = typingsToInstall_2[_a];
if (!installedPackages[toInstall]) {
if (_this.log.isEnabled()) {
_this.log.writeLine("New missing typing package '" + toInstall + "'");
@@ -6429,8 +6565,8 @@ var ts;
this.installRunCount++;
var execInstallCmdCount = 0;
var filteredTypings = [];
for (var _i = 0, typingsToInstall_2 = typingsToInstall; _i < typingsToInstall_2.length; _i++) {
var typing = typingsToInstall_2[_i];
for (var _i = 0, typingsToInstall_3 = typingsToInstall; _i < typingsToInstall_3.length; _i++) {
var typing = typingsToInstall_3[_i];
execNpmViewTyping(this, typing);
}
function execNpmViewTyping(self, typing) {
@@ -6553,13 +6689,14 @@ var ts;
var NodeTypingsInstaller = (function (_super) {
__extends(NodeTypingsInstaller, _super);
function NodeTypingsInstaller(globalTypingsCacheLocation, throttleLimit, log) {
_super.call(this, globalTypingsCacheLocation, getNPMLocation(process.argv[0]), ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log);
this.installTypingHost = ts.sys;
if (this.log.isEnabled()) {
this.log.writeLine("Process id: " + process.pid);
var _this = _super.call(this, globalTypingsCacheLocation, getNPMLocation(process.argv[0]), ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log) || this;
_this.installTypingHost = ts.sys;
if (_this.log.isEnabled()) {
_this.log.writeLine("Process id: " + process.pid);
}
var exec = require("child_process").exec;
this.exec = exec;
_this.exec = exec;
return _this;
}
NodeTypingsInstaller.prototype.init = function () {
var _this = this;
+150
View File
@@ -0,0 +1,150 @@
/// <reference types="node"/>
import * as ts from "../lib/typescript";
import * as path from "path";
function endsWith(s: string, suffix: string) {
return s.lastIndexOf(suffix, s.length - suffix.length) !== -1;
}
class DeclarationsWalker {
private visitedTypes: ts.Type[] = [];
private text = "";
private constructor(private typeChecker: ts.TypeChecker, private protocolFile: ts.SourceFile) {
}
static getExtraDeclarations(typeChecker: ts.TypeChecker, protocolFile: ts.SourceFile): string {
let text = "declare namespace ts.server.protocol {\n";
var walker = new DeclarationsWalker(typeChecker, protocolFile);
walker.visitTypeNodes(protocolFile);
return walker.text
? `declare namespace ts.server.protocol {\n${walker.text}}`
: "";
}
private processType(type: ts.Type): void {
if (this.visitedTypes.indexOf(type) >= 0) {
return;
}
this.visitedTypes.push(type);
let s = type.aliasSymbol || type.getSymbol();
if (!s) {
return;
}
if (s.name === "Array") {
// we should process type argument instead
return this.processType((<any>type).typeArguments[0]);
}
else {
for (const decl of s.getDeclarations()) {
const sourceFile = decl.getSourceFile();
if (sourceFile === this.protocolFile || path.basename(sourceFile.fileName) === "lib.d.ts") {
return;
}
// splice declaration in final d.ts file
let text = decl.getFullText();
if (decl.kind === ts.SyntaxKind.EnumDeclaration && !(decl.flags & ts.NodeFlags.Const)) {
// patch enum declaration to make them constan
const declStart = decl.getStart() - decl.getFullStart();
const prefix = text.substring(0, declStart);
const suffix = text.substring(declStart + "enum".length, decl.getEnd() - decl.getFullStart());
text = prefix + "const enum" + suffix;
}
this.text += `${text}\n`;
// recursively pull all dependencies into result dts file
this.visitTypeNodes(decl);
}
}
}
private visitTypeNodes(node: ts.Node) {
if (node.parent) {
switch (node.parent.kind) {
case ts.SyntaxKind.VariableDeclaration:
case ts.SyntaxKind.MethodDeclaration:
case ts.SyntaxKind.MethodSignature:
case ts.SyntaxKind.PropertyDeclaration:
case ts.SyntaxKind.PropertySignature:
case ts.SyntaxKind.Parameter:
case ts.SyntaxKind.IndexSignature:
if (((<ts.VariableDeclaration | ts.MethodDeclaration | ts.PropertyDeclaration | ts.ParameterDeclaration | ts.PropertySignature | ts.MethodSignature | ts.IndexSignatureDeclaration>node.parent).type) === node) {
const type = this.typeChecker.getTypeAtLocation(node);
if (type && !(type.flags & ts.TypeFlags.TypeParameter)) {
this.processType(type);
}
}
break;
}
}
ts.forEachChild(node, n => this.visitTypeNodes(n));
}
}
function generateProtocolFile(protocolTs: string, typeScriptServicesDts: string): string {
const options = { target: ts.ScriptTarget.ES5, declaration: true, noResolve: true, types: <string[]>[], stripInternal: true };
/**
* 1st pass - generate a program from protocol.ts and typescriptservices.d.ts and emit core version of protocol.d.ts with all internal members stripped
* @return text of protocol.d.t.s
*/
function getInitialDtsFileForProtocol() {
const program = ts.createProgram([protocolTs, typeScriptServicesDts], options);
let protocolDts: string;
program.emit(program.getSourceFile(protocolTs), (file, content) => {
if (endsWith(file, ".d.ts")) {
protocolDts = content;
}
});
if (protocolDts === undefined) {
throw new Error(`Declaration file for protocol.ts is not generated`)
}
return protocolDts;
}
const protocolFileName = "protocol.d.ts";
/**
* Second pass - generate a program from protocol.d.ts and typescriptservices.d.ts, then augment core protocol.d.ts with extra types from typescriptservices.d.ts
*/
function getProgramWithProtocolText(protocolDts: string, includeTypeScriptServices: boolean) {
const host = ts.createCompilerHost(options);
const originalGetSourceFile = host.getSourceFile;
host.getSourceFile = (fileName) => {
if (fileName === protocolFileName) {
return ts.createSourceFile(fileName, protocolDts, options.target);
}
return originalGetSourceFile.apply(host, [fileName]);
}
const rootFiles = includeTypeScriptServices ? [protocolFileName, typeScriptServicesDts] : [protocolFileName];
return ts.createProgram(rootFiles, options, host);
}
let protocolDts = getInitialDtsFileForProtocol();
const program = getProgramWithProtocolText(protocolDts, /*includeTypeScriptServices*/ true);
const protocolFile = program.getSourceFile("protocol.d.ts");
const extraDeclarations = DeclarationsWalker.getExtraDeclarations(program.getTypeChecker(), protocolFile);
if (extraDeclarations) {
protocolDts += extraDeclarations;
}
// do sanity check and try to compile generated text as standalone program
const sanityCheckProgram = getProgramWithProtocolText(protocolDts, /*includeTypeScriptServices*/ false);
const diagnostics = [...program.getSyntacticDiagnostics(), ...program.getSemanticDiagnostics(), ...program.getGlobalDiagnostics()];
if (diagnostics.length) {
const flattenedDiagnostics = diagnostics.map(d => ts.flattenDiagnosticMessageText(d.messageText, "\n")).join("\n");
throw new Error(`Unexpected errors during sanity check: ${flattenedDiagnostics}`);
}
return protocolDts;
}
if (process.argv.length < 5) {
console.log(`Expected 3 arguments: path to 'protocol.ts', path to 'typescriptservices.d.ts' and path to output file`);
process.exit(1);
}
const protocolTs = process.argv[2];
const typeScriptServicesDts = process.argv[3];
const outputFile = process.argv[4];
const generatedProtocolDts = generateProtocolFile(protocolTs, typeScriptServicesDts);
ts.sys.writeFile(outputFile, generatedProtocolDts);
+175 -82
View File
@@ -84,6 +84,7 @@ namespace ts {
IsFunctionExpression = 1 << 4,
HasLocals = 1 << 5,
IsInterface = 1 << 6,
IsObjectLiteralOrClassExpressionMethod = 1 << 7,
}
const binder = createBinder();
@@ -121,7 +122,8 @@ namespace ts {
// If this file is an external module, then it is automatically in strict-mode according to
// ES6. If it is not an external module, then we'll determine if it is in strict mode or
// not depending on if we see "use strict" in certain places (or if we hit a class/namespace).
// not depending on if we see "use strict" in certain places or if we hit a class/namespace
// or if compiler options contain alwaysStrict.
let inStrictMode: boolean;
let symbolCount = 0;
@@ -139,7 +141,7 @@ namespace ts {
file = f;
options = opts;
languageVersion = getEmitScriptTarget(options);
inStrictMode = !!file.externalModuleIndicator;
inStrictMode = bindInStrictMode(file, opts);
classifiableNames = new StringSet();
symbolCount = 0;
skipTransformFlagAggregation = isDeclarationFile(file);
@@ -174,6 +176,16 @@ namespace ts {
return bindSourceFile;
function bindInStrictMode(file: SourceFile, opts: CompilerOptions): boolean {
if (opts.alwaysStrict && !isDeclarationFile(file)) {
// bind in strict mode source files with alwaysStrict option
return true;
}
else {
return !!file.externalModuleIndicator;
}
}
function createSymbol(flags: SymbolFlags, name: string): Symbol {
symbolCount++;
return new Symbol(flags, name);
@@ -486,8 +498,8 @@ namespace ts {
}
else {
currentFlow = { flags: FlowFlags.Start };
if (containerFlags & ContainerFlags.IsFunctionExpression) {
(<FlowStart>currentFlow).container = <FunctionExpression | ArrowFunction>node;
if (containerFlags & (ContainerFlags.IsFunctionExpression | ContainerFlags.IsObjectLiteralOrClassExpressionMethod)) {
(<FlowStart>currentFlow).container = <FunctionExpression | ArrowFunction | MethodDeclaration>node;
}
currentReturnTarget = undefined;
}
@@ -773,6 +785,15 @@ namespace ts {
};
}
function createFlowArrayMutation(antecedent: FlowNode, node: CallExpression | BinaryExpression): FlowNode {
setFlowNodeReferenced(antecedent);
return <FlowArrayMutation>{
flags: FlowFlags.ArrayMutation,
antecedent,
node
};
}
function finishFlowLabel(flow: FlowLabel): FlowNode {
const antecedents = flow.antecedents;
if (!antecedents) {
@@ -1153,6 +1174,12 @@ namespace ts {
forEachChild(node, bind);
if (operator === SyntaxKind.EqualsToken && !isAssignmentTarget(node)) {
bindAssignmentTargetFlow(node.left);
if (node.left.kind === SyntaxKind.ElementAccessExpression) {
const elementAccess = <ElementAccessExpression>node.left;
if (isNarrowableOperand(elementAccess.expression)) {
currentFlow = createFlowArrayMutation(currentFlow, node);
}
}
}
}
}
@@ -1213,6 +1240,12 @@ namespace ts {
else {
forEachChild(node, bind);
}
if (node.expression.kind === SyntaxKind.PropertyAccessExpression) {
const propertyAccess = <PropertyAccessExpression>node.expression;
if (isNarrowableOperand(propertyAccess.expression) && isPushOrUnshiftIdentifier(propertyAccess.name)) {
currentFlow = createFlowArrayMutation(currentFlow, node);
}
}
}
function getContainerFlags(node: Node): ContainerFlags {
@@ -1237,9 +1270,12 @@ namespace ts {
case SyntaxKind.SourceFile:
return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals;
case SyntaxKind.MethodDeclaration:
if (isObjectLiteralOrClassExpressionMethod(node)) {
return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals | ContainerFlags.IsFunctionLike | ContainerFlags.IsObjectLiteralOrClassExpressionMethod;
}
case SyntaxKind.Constructor:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
@@ -1648,7 +1684,7 @@ namespace ts {
}
function checkStrictModeFunctionDeclaration(node: FunctionDeclaration) {
if (languageVersion < ScriptTarget.ES6) {
if (languageVersion < ScriptTarget.ES2015) {
// Report error if function is not top level function declaration
if (blockScopeContainer.kind !== SyntaxKind.SourceFile &&
blockScopeContainer.kind !== SyntaxKind.ModuleDeclaration &&
@@ -2238,6 +2274,10 @@ namespace ts {
}
}
if (currentFlow && isObjectLiteralOrClassExpressionMethod(node)) {
node.flowNode = currentFlow;
}
return hasDynamicName(node)
? bindAnonymousDeclaration(node, symbolFlags, "__computed")
: declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
@@ -2311,6 +2351,9 @@ namespace ts {
case SyntaxKind.CallExpression:
return computeCallExpression(<CallExpression>node, subtreeFlags);
case SyntaxKind.NewExpression:
return computeNewExpression(<NewExpression>node, subtreeFlags);
case SyntaxKind.ModuleDeclaration:
return computeModuleDeclaration(<ModuleDeclaration>node, subtreeFlags);
@@ -2388,11 +2431,15 @@ namespace ts {
const expression = node.expression;
const expressionKind = expression.kind;
if (node.typeArguments) {
transformFlags |= TransformFlags.AssertTypeScript;
}
if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression
|| isSuperOrSuperProperty(expression, expressionKind)) {
// If the this node contains a SpreadElementExpression, or is a super call, then it is an ES6
// node.
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
@@ -2414,6 +2461,21 @@ namespace ts {
return false;
}
function computeNewExpression(node: NewExpression, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
if (node.typeArguments) {
transformFlags |= TransformFlags.AssertTypeScript;
}
if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) {
// If the this node contains a SpreadElementExpression then it is an ES6
// node.
transformFlags |= TransformFlags.AssertES2015;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.ArrayLiteralOrCallOrNewExcludes;
}
function computeBinaryExpression(node: BinaryExpression, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const operatorTokenKind = node.operatorToken.kind;
@@ -2423,12 +2485,12 @@ namespace ts {
&& (leftKind === SyntaxKind.ObjectLiteralExpression
|| leftKind === SyntaxKind.ArrayLiteralExpression)) {
// Destructuring assignments are ES6 syntax.
transformFlags |= TransformFlags.AssertES6 | TransformFlags.DestructuringAssignment;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.DestructuringAssignment;
}
else if (operatorTokenKind === SyntaxKind.AsteriskAsteriskToken
|| operatorTokenKind === SyntaxKind.AsteriskAsteriskEqualsToken) {
// Exponentiation is ES7 syntax.
transformFlags |= TransformFlags.AssertES7;
// Exponentiation is ES2016 syntax.
transformFlags |= TransformFlags.AssertES2016;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
@@ -2442,13 +2504,12 @@ namespace ts {
const initializer = node.initializer;
const dotDotDotToken = node.dotDotDotToken;
// If the parameter has a question token, then it is TypeScript syntax.
if (node.questionToken) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// If the parameter's name is 'this', then it is TypeScript syntax.
if (subtreeFlags & TransformFlags.ContainsDecorators || isThisIdentifier(name)) {
// The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript
// syntax.
if (node.questionToken
|| node.type
|| subtreeFlags & TransformFlags.ContainsDecorators
|| isThisIdentifier(name)) {
transformFlags |= TransformFlags.AssertTypeScript;
}
@@ -2460,7 +2521,7 @@ namespace ts {
// 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 & TransformFlags.ContainsBindingPattern || initializer || dotDotDotToken) {
transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsDefaultValueAssignments;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsDefaultValueAssignments;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
@@ -2501,13 +2562,14 @@ namespace ts {
}
else {
// A ClassDeclaration is ES6 syntax.
transformFlags = subtreeFlags | TransformFlags.AssertES6;
transformFlags = subtreeFlags | TransformFlags.AssertES2015;
// A class with a parameter property assignment, property initializer, or decorator is
// TypeScript syntax.
// An exported declaration may be TypeScript syntax.
if ((subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask)
|| (modifierFlags & ModifierFlags.Export)) {
|| (modifierFlags & ModifierFlags.Export)
|| node.typeParameters) {
transformFlags |= TransformFlags.AssertTypeScript;
}
@@ -2524,11 +2586,12 @@ namespace ts {
function computeClassExpression(node: ClassExpression, subtreeFlags: TransformFlags) {
// A ClassExpression is ES6 syntax.
let transformFlags = subtreeFlags | TransformFlags.AssertES6;
let transformFlags = subtreeFlags | TransformFlags.AssertES2015;
// A class with a parameter property assignment, property initializer, or decorator is
// TypeScript syntax.
if (subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask) {
if (subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask
|| node.typeParameters) {
transformFlags |= TransformFlags.AssertTypeScript;
}
@@ -2548,7 +2611,7 @@ namespace ts {
switch (node.token) {
case SyntaxKind.ExtendsKeyword:
// An `extends` HeritageClause is ES6 syntax.
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
break;
case SyntaxKind.ImplementsKeyword:
@@ -2568,7 +2631,7 @@ namespace ts {
function computeExpressionWithTypeArguments(node: ExpressionWithTypeArguments, subtreeFlags: TransformFlags) {
// An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
// extends clause of a class.
let transformFlags = subtreeFlags | TransformFlags.AssertES6;
let transformFlags = subtreeFlags | TransformFlags.AssertES2015;
// If an ExpressionWithTypeArguments contains type arguments, then it
// is TypeScript syntax.
@@ -2582,10 +2645,10 @@ namespace ts {
function computeConstructor(node: ConstructorDeclaration, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const body = node.body;
if (body === undefined) {
// An overload constructor is TypeScript syntax.
// TypeScript-specific modifiers and overloads are TypeScript syntax
if (hasModifier(node, ModifierFlags.TypeScriptModifier)
|| !node.body) {
transformFlags |= TransformFlags.AssertTypeScript;
}
@@ -2595,23 +2658,25 @@ namespace ts {
function computeMethod(node: MethodDeclaration, subtreeFlags: TransformFlags) {
// A MethodDeclaration is ES6 syntax.
let transformFlags = subtreeFlags | TransformFlags.AssertES6;
const modifierFlags = getModifierFlags(node);
const body = node.body;
const typeParameters = node.typeParameters;
const asteriskToken = node.asteriskToken;
let transformFlags = subtreeFlags | TransformFlags.AssertES2015;
// A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded,
// generic, or has a decorator.
if (!body
|| typeParameters
|| (modifierFlags & (ModifierFlags.Async | ModifierFlags.Abstract))
|| (subtreeFlags & TransformFlags.ContainsDecorators)) {
// Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
// overloads are TypeScript syntax.
if (node.decorators
|| hasModifier(node, ModifierFlags.TypeScriptModifier)
|| node.typeParameters
|| node.type
|| !node.body) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// An async method declaration is ES2017 syntax.
if (hasModifier(node, ModifierFlags.Async)) {
transformFlags |= TransformFlags.AssertES2017;
}
// Currently, we only support generators that were originally async function bodies.
if (asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) {
if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) {
transformFlags |= TransformFlags.AssertGenerator;
}
@@ -2621,14 +2686,13 @@ namespace ts {
function computeAccessor(node: AccessorDeclaration, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const modifierFlags = getModifierFlags(node);
const body = node.body;
// A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded,
// generic, or has a decorator.
if (!body
|| (modifierFlags & (ModifierFlags.Async | ModifierFlags.Abstract))
|| (subtreeFlags & TransformFlags.ContainsDecorators)) {
// Decorators, TypeScript-specific modifiers, type annotations, and overloads are
// TypeScript syntax.
if (node.decorators
|| hasModifier(node, ModifierFlags.TypeScriptModifier)
|| node.type
|| !node.body) {
transformFlags |= TransformFlags.AssertTypeScript;
}
@@ -2654,7 +2718,6 @@ namespace ts {
let transformFlags: TransformFlags;
const modifierFlags = getModifierFlags(node);
const body = node.body;
const asteriskToken = node.asteriskToken;
if (!body || (modifierFlags & ModifierFlags.Ambient)) {
// An ambient declaration is TypeScript syntax.
@@ -2666,19 +2729,27 @@ namespace ts {
// If a FunctionDeclaration is exported, then it is either ES6 or TypeScript syntax.
if (modifierFlags & ModifierFlags.Export) {
transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES2015;
}
// If a FunctionDeclaration is async, then it is TypeScript syntax.
if (modifierFlags & ModifierFlags.Async) {
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (modifierFlags & ModifierFlags.TypeScriptModifier
|| node.typeParameters
|| node.type) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// An async function declaration is ES2017 syntax.
if (modifierFlags & ModifierFlags.Async) {
transformFlags |= TransformFlags.AssertES2017;
}
// 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 & TransformFlags.ES6FunctionSyntaxMask) {
transformFlags |= TransformFlags.AssertES6;
if (subtreeFlags & TransformFlags.ES2015FunctionSyntaxMask) {
transformFlags |= TransformFlags.AssertES2015;
}
// If a FunctionDeclaration is generator function and is the body of a
@@ -2686,7 +2757,7 @@ namespace ts {
// down-level generator.
// Currently we do not support transforming any other generator fucntions
// down level.
if (asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) {
if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) {
transformFlags |= TransformFlags.AssertGenerator;
}
}
@@ -2697,19 +2768,25 @@ namespace ts {
function computeFunctionExpression(node: FunctionExpression, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const modifierFlags = getModifierFlags(node);
const asteriskToken = node.asteriskToken;
// An async function expression is TypeScript syntax.
if (modifierFlags & ModifierFlags.Async) {
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (hasModifier(node, ModifierFlags.TypeScriptModifier)
|| node.typeParameters
|| node.type) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// An async function expression is ES2017 syntax.
if (hasModifier(node, ModifierFlags.Async)) {
transformFlags |= TransformFlags.AssertES2017;
}
// 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 & TransformFlags.ES6FunctionSyntaxMask) {
transformFlags |= TransformFlags.AssertES6;
if (subtreeFlags & TransformFlags.ES2015FunctionSyntaxMask) {
transformFlags |= TransformFlags.AssertES2015;
}
// If a FunctionExpression is generator function and is the body of a
@@ -2717,7 +2794,7 @@ namespace ts {
// down-level generator.
// Currently we do not support transforming any other generator fucntions
// down level.
if (asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) {
if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) {
transformFlags |= TransformFlags.AssertGenerator;
}
@@ -2727,14 +2804,21 @@ namespace ts {
function computeArrowFunction(node: ArrowFunction, subtreeFlags: TransformFlags) {
// An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
let transformFlags = subtreeFlags | TransformFlags.AssertES6;
const modifierFlags = getModifierFlags(node);
let transformFlags = subtreeFlags | TransformFlags.AssertES2015;
// An async arrow function is TypeScript syntax.
if (modifierFlags & ModifierFlags.Async) {
// TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
// syntax.
if (hasModifier(node, ModifierFlags.TypeScriptModifier)
|| node.typeParameters
|| node.type) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// An async arrow function is ES2017 syntax.
if (hasModifier(node, ModifierFlags.Async)) {
transformFlags |= TransformFlags.AssertES2017;
}
// If an ArrowFunction contains a lexical this, its container must capture the lexical this.
if (subtreeFlags & TransformFlags.ContainsLexicalThis) {
transformFlags |= TransformFlags.ContainsCapturedLexicalThis;
@@ -2765,7 +2849,12 @@ namespace ts {
// A VariableDeclaration with a binding pattern is ES6 syntax.
if (nameKind === SyntaxKind.ObjectBindingPattern || nameKind === SyntaxKind.ArrayBindingPattern) {
transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBindingPattern;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
}
// Type annotations are TypeScript syntax.
if (node.type) {
transformFlags |= TransformFlags.AssertTypeScript;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
@@ -2786,11 +2875,11 @@ namespace ts {
// If a VariableStatement is exported, then it is either ES6 or TypeScript syntax.
if (modifierFlags & ModifierFlags.Export) {
transformFlags |= TransformFlags.AssertES6 | TransformFlags.AssertTypeScript;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.AssertTypeScript;
}
if (declarationListTransformFlags & TransformFlags.ContainsBindingPattern) {
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
}
@@ -2804,7 +2893,7 @@ namespace ts {
// A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
if (subtreeFlags & TransformFlags.ContainsBlockScopedBinding
&& isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
@@ -2830,7 +2919,7 @@ namespace ts {
// 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 & TransformFlags.DestructuringAssignment) {
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
@@ -2853,12 +2942,12 @@ namespace ts {
let transformFlags = subtreeFlags | TransformFlags.ContainsHoistedDeclarationOrCompletion;
if (subtreeFlags & TransformFlags.ContainsBindingPattern) {
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
// If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
if (node.flags & NodeFlags.BlockScoped) {
transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBlockScopedBinding;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBlockScopedBinding;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
@@ -2871,14 +2960,18 @@ namespace ts {
let excludeFlags = TransformFlags.NodeExcludes;
switch (kind) {
case SyntaxKind.AsyncKeyword:
case SyntaxKind.AwaitExpression:
// async/await is ES2017 syntax
transformFlags |= TransformFlags.AssertES2017;
break;
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.AbstractKeyword:
case SyntaxKind.DeclareKeyword:
case SyntaxKind.AsyncKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.AwaitExpression:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.EnumMember:
case SyntaxKind.TypeAssertionExpression:
@@ -2903,7 +2996,7 @@ namespace ts {
case SyntaxKind.ExportKeyword:
// This node is both ES6 and TypeScript syntax.
transformFlags |= TransformFlags.AssertES6 | TransformFlags.AssertTypeScript;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.AssertTypeScript;
break;
case SyntaxKind.DefaultKeyword:
@@ -2916,12 +3009,12 @@ namespace ts {
case SyntaxKind.ShorthandPropertyAssignment:
case SyntaxKind.ForOfStatement:
// These nodes are ES6 syntax.
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
break;
case SyntaxKind.YieldExpression:
// This node is ES6 syntax.
transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsYield;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsYield;
break;
case SyntaxKind.AnyKeyword:
@@ -2982,7 +3075,7 @@ namespace ts {
case SyntaxKind.SuperKeyword:
// This node is ES6 syntax.
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
break;
case SyntaxKind.ThisKeyword:
@@ -2993,7 +3086,7 @@ namespace ts {
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
// These nodes are ES6 syntax.
transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBindingPattern;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
break;
case SyntaxKind.Decorator:
@@ -3006,7 +3099,7 @@ namespace ts {
if (subtreeFlags & TransformFlags.ContainsComputedPropertyName) {
// If an ObjectLiteralExpression contains a ComputedPropertyName, then it
// is an ES6 node.
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) {
@@ -3023,7 +3116,7 @@ namespace ts {
if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) {
// If the this node contains a SpreadElementExpression, then it is an ES6
// node.
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
break;
@@ -3034,14 +3127,14 @@ namespace ts {
case SyntaxKind.ForInStatement:
// A loop containing a block scoped binding *may* need to be transformed from ES6.
if (subtreeFlags & TransformFlags.ContainsBlockScopedBinding) {
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
break;
case SyntaxKind.SourceFile:
if (subtreeFlags & TransformFlags.ContainsCapturedLexicalThis) {
transformFlags |= TransformFlags.AssertES6;
transformFlags |= TransformFlags.AssertES2015;
}
break;
+286 -81
View File
@@ -115,6 +115,7 @@ namespace ts {
const intersectionTypes = new StringMap<IntersectionType>();
const stringLiteralTypes = new StringMap<LiteralType>();
const numericLiteralTypes = new StringMap<LiteralType>();
const evolvingArrayTypes: AnonymousType[] = [];
const unknownSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "unknown");
const resolvingSymbol = createSymbol(SymbolFlags.Transient, "__resolving__");
@@ -176,6 +177,7 @@ namespace ts {
let globalBooleanType: ObjectType;
let globalRegExpType: ObjectType;
let anyArrayType: Type;
let autoArrayType: Type;
let anyReadonlyArrayType: Type;
// The library files are only loaded when the feature is used.
@@ -923,7 +925,7 @@ namespace ts {
if (result && isInExternalModule && (meaning & SymbolFlags.Value) === SymbolFlags.Value) {
const decls = result.declarations;
if (decls && decls.length === 1 && decls[0].kind === SyntaxKind.NamespaceExportDeclaration) {
error(errorLocation, Diagnostics.Identifier_0_must_be_imported_from_a_module, name);
error(errorLocation, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name);
}
}
}
@@ -1475,6 +1477,10 @@ namespace ts {
function getExportsForModule(moduleSymbol: Symbol): SymbolTable {
const visitedSymbols: Symbol[] = [];
// A module defined by an 'export=' consists on one export that needs to be resolved
moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
return visit(moduleSymbol) || moduleSymbol.exports;
// The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
@@ -3065,9 +3071,14 @@ namespace ts {
return undefined;
}
function isAutoVariableInitializer(initializer: Expression) {
const expr = initializer && skipParentheses(initializer);
return !expr || expr.kind === SyntaxKind.NullKeyword || expr.kind === SyntaxKind.Identifier && getResolvedSymbol(<Identifier>expr) === undefinedSymbol;
function isNullOrUndefined(node: Expression) {
const expr = skipParentheses(node);
return expr.kind === SyntaxKind.NullKeyword || expr.kind === SyntaxKind.Identifier && getResolvedSymbol(<Identifier>expr) === undefinedSymbol;
}
function isEmptyArrayLiteral(node: Expression) {
const expr = skipParentheses(node);
return expr.kind === SyntaxKind.ArrayLiteralExpression && (<ArrayLiteralExpression>expr).elements.length === 0;
}
function addOptionality(type: Type, optional: boolean): Type {
@@ -3108,12 +3119,18 @@ namespace ts {
return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality);
}
// Use control flow type inference for non-ambient, non-exported var or let variables with no initializer
// or a 'null' or 'undefined' initializer.
if (declaration.kind === SyntaxKind.VariableDeclaration && !isBindingPattern(declaration.name) &&
!(getCombinedNodeFlags(declaration) & NodeFlags.Const) && !(getCombinedModifierFlags(declaration) & ModifierFlags.Export) &&
!isInAmbientContext(declaration) && isAutoVariableInitializer(declaration.initializer)) {
return autoType;
!(getCombinedModifierFlags(declaration) & ModifierFlags.Export) && !isInAmbientContext(declaration)) {
// Use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
// initializer or a 'null' or 'undefined' initializer.
if (!(getCombinedNodeFlags(declaration) & NodeFlags.Const) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
return autoType;
}
// Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array
// literal initializer.
if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
return autoArrayType;
}
}
if (declaration.kind === SyntaxKind.Parameter) {
@@ -3216,7 +3233,7 @@ namespace ts {
const elements = pattern.elements;
const lastElement = lastOrUndefined(elements);
if (elements.length === 0 || (!isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) {
return languageVersion >= ScriptTarget.ES6 ? createIterableType(anyType) : anyArrayType;
return languageVersion >= ScriptTarget.ES2015 ? createIterableType(anyType) : anyArrayType;
}
// If the pattern has at least one element, and no rest element, then it should imply a tuple type.
const elementTypes = map(elements, e => isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors));
@@ -7429,7 +7446,7 @@ namespace ts {
type.flags & TypeFlags.NumberLiteral ? numberType :
type.flags & TypeFlags.BooleanLiteral ? booleanType :
type.flags & TypeFlags.EnumLiteral ? (<EnumLiteralType>type).baseType :
type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(map((<UnionType>type).types, getBaseTypeOfLiteralType)) :
type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(sameMap((<UnionType>type).types, getBaseTypeOfLiteralType)) :
type;
}
@@ -7438,7 +7455,7 @@ namespace ts {
type.flags & TypeFlags.NumberLiteral && type.flags & TypeFlags.FreshLiteral ? numberType :
type.flags & TypeFlags.BooleanLiteral ? booleanType :
type.flags & TypeFlags.EnumLiteral ? (<EnumLiteralType>type).baseType :
type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(map((<UnionType>type).types, getWidenedLiteralType)) :
type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(sameMap((<UnionType>type).types, getWidenedLiteralType)) :
type;
}
@@ -7577,10 +7594,10 @@ namespace ts {
return getWidenedTypeOfObjectLiteral(type);
}
if (type.flags & TypeFlags.Union) {
return getUnionType(map((<UnionType>type).types, getWidenedConstituentType));
return getUnionType(sameMap((<UnionType>type).types, getWidenedConstituentType));
}
if (isArrayType(type) || isTupleType(type)) {
return createTypeReference((<TypeReference>type).target, map((<TypeReference>type).typeArguments, getWidenedType));
return createTypeReference((<TypeReference>type).target, sameMap((<TypeReference>type).typeArguments, getWidenedType));
}
}
return type;
@@ -7998,7 +8015,7 @@ namespace ts {
const widenLiteralTypes = context.inferences[index].topLevel &&
!hasPrimitiveConstraint(signature.typeParameters[index]) &&
(context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index]));
const baseInferences = widenLiteralTypes ? map(inferences, getWidenedLiteralType) : inferences;
const baseInferences = widenLiteralTypes ? sameMap(inferences, getWidenedLiteralType) : inferences;
// Infer widened union or supertype, or the unknown type for no common supertype
const unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, /*subtypeReduction*/ true) : getCommonSupertype(baseInferences);
inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType;
@@ -8401,6 +8418,13 @@ namespace ts {
getAssignedType(<Expression>node);
}
function isEmptyArrayAssignment(node: VariableDeclaration | BindingElement | Expression) {
return node.kind === SyntaxKind.VariableDeclaration && (<VariableDeclaration>node).initializer &&
isEmptyArrayLiteral((<VariableDeclaration>node).initializer) ||
node.kind !== SyntaxKind.BindingElement && node.parent.kind === SyntaxKind.BinaryExpression &&
isEmptyArrayLiteral((<BinaryExpression>node.parent).right);
}
function getReferenceCandidate(node: Expression): Expression {
switch (node.kind) {
case SyntaxKind.ParenthesizedExpression:
@@ -8416,6 +8440,14 @@ namespace ts {
return node;
}
function getReferenceRoot(node: Node): Node {
const parent = node.parent;
return parent.kind === SyntaxKind.ParenthesizedExpression ||
parent.kind === SyntaxKind.BinaryExpression && (<BinaryExpression>parent).operatorToken.kind === SyntaxKind.EqualsToken && (<BinaryExpression>parent).left === node ||
parent.kind === SyntaxKind.BinaryExpression && (<BinaryExpression>parent).operatorToken.kind === SyntaxKind.CommaToken && (<BinaryExpression>parent).right === node ?
getReferenceRoot(parent) : node;
}
function getTypeOfSwitchClause(clause: CaseClause | DefaultClause) {
if (clause.kind === SyntaxKind.CaseClause) {
const caseType = getRegularTypeOfLiteralType(checkExpression((<CaseClause>clause).expression));
@@ -8467,6 +8499,28 @@ namespace ts {
return f(type) ? type : neverType;
}
function mapType(type: Type, f: (t: Type) => Type): Type {
return type.flags & TypeFlags.Union ? getUnionType(map((<UnionType>type).types, f)) : f(type);
}
function extractTypesOfKind(type: Type, kind: TypeFlags) {
return filterType(type, t => (t.flags & kind) !== 0);
}
// Return a new type in which occurrences of the string and number primitive types in
// typeWithPrimitives have been replaced with occurrences of string literals and numeric
// literals in typeWithLiterals, respectively.
function replacePrimitivesWithLiterals(typeWithPrimitives: Type, typeWithLiterals: Type) {
if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, TypeFlags.StringLiteral) ||
isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, TypeFlags.NumberLiteral)) {
return mapType(typeWithPrimitives, t =>
t.flags & TypeFlags.String ? extractTypesOfKind(typeWithLiterals, TypeFlags.String | TypeFlags.StringLiteral) :
t.flags & TypeFlags.Number ? extractTypesOfKind(typeWithLiterals, TypeFlags.Number | TypeFlags.NumberLiteral) :
t);
}
return typeWithPrimitives;
}
function isIncomplete(flowType: FlowType) {
return flowType.flags === 0;
}
@@ -8479,21 +8533,113 @@ namespace ts {
return incomplete ? { flags: 0, type } : type;
}
// An evolving array type tracks the element types that have so far been seen in an
// 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving
// array types are ultimately converted into manifest array types (using getFinalArrayType)
// and never escape the getFlowTypeOfReference function.
function createEvolvingArrayType(elementType: Type): AnonymousType {
const result = <AnonymousType>createObjectType(TypeFlags.Anonymous);
result.elementType = elementType;
return result;
}
function getEvolvingArrayType(elementType: Type): AnonymousType {
return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
}
// When adding evolving array element types we do not perform subtype reduction. Instead,
// we defer subtype reduction until the evolving array type is finalized into a manifest
// array type.
function addEvolvingArrayElementType(evolvingArrayType: AnonymousType, node: Expression): AnonymousType {
const elementType = getBaseTypeOfLiteralType(checkExpression(node));
return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
}
function isEvolvingArrayType(type: Type) {
return !!(type.flags & TypeFlags.Anonymous && (<AnonymousType>type).elementType);
}
function createFinalArrayType(elementType: Type) {
return elementType.flags & TypeFlags.Never ?
autoArrayType :
createArrayType(elementType.flags & TypeFlags.Union ?
getUnionType((<UnionType>elementType).types, /*subtypeReduction*/ true) :
elementType);
}
// We perform subtype reduction upon obtaining the final array type from an evolving array type.
function getFinalArrayType(evolvingArrayType: AnonymousType): Type {
return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
}
function finalizeEvolvingArrayType(type: Type): Type {
return isEvolvingArrayType(type) ? getFinalArrayType(<AnonymousType>type) : type;
}
function getElementTypeOfEvolvingArrayType(type: Type) {
return isEvolvingArrayType(type) ? (<AnonymousType>type).elementType : neverType;
}
function isEvolvingArrayTypeList(types: Type[]) {
let hasEvolvingArrayType = false;
for (const t of types) {
if (!(t.flags & TypeFlags.Never)) {
if (!isEvolvingArrayType(t)) {
return false;
}
hasEvolvingArrayType = true;
}
}
return hasEvolvingArrayType;
}
// At flow control branch or loop junctions, if the type along every antecedent code path
// is an evolving array type, we construct a combined evolving array type. Otherwise we
// finalize all evolving array types.
function getUnionOrEvolvingArrayType(types: Type[], subtypeReduction: boolean) {
return isEvolvingArrayTypeList(types) ?
getEvolvingArrayType(getUnionType(map(types, getElementTypeOfEvolvingArrayType))) :
getUnionType(sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
}
// Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
// 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
function isEvolvingArrayOperationTarget(node: Node) {
const root = getReferenceRoot(node);
const parent = root.parent;
const isLengthPushOrUnshift = parent.kind === SyntaxKind.PropertyAccessExpression && (
(<PropertyAccessExpression>parent).name.text === "length" ||
parent.parent.kind === SyntaxKind.CallExpression && isPushOrUnshiftIdentifier((<PropertyAccessExpression>parent).name));
const isElementAssignment = parent.kind === SyntaxKind.ElementAccessExpression &&
(<ElementAccessExpression>parent).expression === root &&
parent.parent.kind === SyntaxKind.BinaryExpression &&
(<BinaryExpression>parent.parent).operatorToken.kind === SyntaxKind.EqualsToken &&
(<BinaryExpression>parent.parent).left === parent &&
!isAssignmentTarget(parent.parent) &&
isTypeAnyOrAllConstituentTypesHaveKind(checkExpression((<ElementAccessExpression>parent).argumentExpression), TypeFlags.NumberLike | TypeFlags.Undefined);
return isLengthPushOrUnshift || isElementAssignment;
}
function getFlowTypeOfReference(reference: Node, declaredType: Type, assumeInitialized: boolean, flowContainer: Node) {
let key: string;
if (!reference.flowNode || assumeInitialized && !(declaredType.flags & TypeFlags.Narrowable)) {
return declaredType;
}
const initialType = assumeInitialized ? declaredType :
declaredType === autoType ? undefinedType :
declaredType === autoType || declaredType === autoArrayType ? undefinedType :
includeFalsyTypes(declaredType, TypeFlags.Undefined);
const visitedFlowStart = visitedFlowCount;
const result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
const evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
visitedFlowCount = visitedFlowStart;
if (reference.parent.kind === SyntaxKind.NonNullExpression && getTypeWithFacts(result, TypeFacts.NEUndefinedOrNull).flags & TypeFlags.Never) {
// When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation,
// we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations
// on empty arrays are possible without implicit any errors and new element types can be inferred without
// type mismatch errors.
const resultType = isEvolvingArrayType(evolvedType) && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType);
if (reference.parent.kind === SyntaxKind.NonNullExpression && getTypeWithFacts(resultType, TypeFacts.NEUndefinedOrNull).flags & TypeFlags.Never) {
return declaredType;
}
return result;
return resultType;
function getTypeAtFlowNode(flow: FlowNode): FlowType {
while (true) {
@@ -8530,6 +8676,13 @@ namespace ts {
getTypeAtFlowBranchLabel(<FlowLabel>flow) :
getTypeAtFlowLoopLabel(<FlowLabel>flow);
}
else if (flow.flags & FlowFlags.ArrayMutation) {
type = getTypeAtFlowArrayMutation(<FlowArrayMutation>flow);
if (!type) {
flow = (<FlowArrayMutation>flow).antecedent;
continue;
}
}
else if (flow.flags & FlowFlags.Start) {
// Check if we should continue with the control flow of the containing function.
const container = (<FlowStart>flow).container;
@@ -8542,8 +8695,8 @@ namespace ts {
}
else {
// Unreachable code errors are reported in the binding phase. Here we
// simply return the declared type to reduce follow-on errors.
type = declaredType;
// simply return the non-auto declared type to reduce follow-on errors.
type = convertAutoToAny(declaredType);
}
if (flow.flags & FlowFlags.Shared) {
// Record visited node and the associated type in the cache.
@@ -8564,9 +8717,17 @@ namespace ts {
const flowType = getTypeAtFlowNode(flow.antecedent);
return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
}
return declaredType === autoType ? getBaseTypeOfLiteralType(getInitialOrAssignedType(node)) :
declaredType.flags & TypeFlags.Union ? getAssignmentReducedType(<UnionType>declaredType, getInitialOrAssignedType(node)) :
declaredType;
if (declaredType === autoType || declaredType === autoArrayType) {
if (isEmptyArrayAssignment(node)) {
return getEvolvingArrayType(neverType);
}
const assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node));
return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
}
if (declaredType.flags & TypeFlags.Union) {
return getAssignmentReducedType(<UnionType>declaredType, getInitialOrAssignedType(node));
}
return declaredType;
}
// We didn't have a direct match. However, if the reference is a dotted name, this
// may be an assignment to a left hand part of the reference. For example, for a
@@ -8579,24 +8740,56 @@ namespace ts {
return undefined;
}
function getTypeAtFlowArrayMutation(flow: FlowArrayMutation): FlowType {
const node = flow.node;
const expr = node.kind === SyntaxKind.CallExpression ?
(<PropertyAccessExpression>(<CallExpression>node).expression).expression :
(<ElementAccessExpression>(<BinaryExpression>node).left).expression;
if (isMatchingReference(reference, getReferenceCandidate(expr))) {
const flowType = getTypeAtFlowNode(flow.antecedent);
const type = getTypeFromFlowType(flowType);
if (isEvolvingArrayType(type)) {
let evolvedType = <AnonymousType>type;
if (node.kind === SyntaxKind.CallExpression) {
for (const arg of (<CallExpression>node).arguments) {
evolvedType = addEvolvingArrayElementType(evolvedType, arg);
}
}
else {
const indexType = checkExpression((<ElementAccessExpression>(<BinaryExpression>node).left).argumentExpression);
if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, TypeFlags.NumberLike | TypeFlags.Undefined)) {
evolvedType = addEvolvingArrayElementType(evolvedType, (<BinaryExpression>node).right);
}
}
return evolvedType === type ? flowType : createFlowType(evolvedType, isIncomplete(flowType));
}
return flowType;
}
return undefined;
}
function getTypeAtFlowCondition(flow: FlowCondition): FlowType {
const flowType = getTypeAtFlowNode(flow.antecedent);
let type = getTypeFromFlowType(flowType);
if (!(type.flags & TypeFlags.Never)) {
// If we have an antecedent type (meaning we're reachable in some way), we first
// attempt to narrow the antecedent type. If that produces the never type, and if
// the antecedent type is incomplete (i.e. a transient type in a loop), then we
// take the type guard as an indication that control *could* reach here once we
// have the complete type. We proceed by switching to the silent never type which
// doesn't report errors when operators are applied to it. Note that this is the
// *only* place a silent never type is ever generated.
const assumeTrue = (flow.flags & FlowFlags.TrueCondition) !== 0;
type = narrowType(type, flow.expression, assumeTrue);
if (type.flags & TypeFlags.Never && isIncomplete(flowType)) {
type = silentNeverType;
}
const type = getTypeFromFlowType(flowType);
if (type.flags & TypeFlags.Never) {
return flowType;
}
return createFlowType(type, isIncomplete(flowType));
// If we have an antecedent type (meaning we're reachable in some way), we first
// attempt to narrow the antecedent type. If that produces the never type, and if
// the antecedent type is incomplete (i.e. a transient type in a loop), then we
// take the type guard as an indication that control *could* reach here once we
// have the complete type. We proceed by switching to the silent never type which
// doesn't report errors when operators are applied to it. Note that this is the
// *only* place a silent never type is ever generated.
const assumeTrue = (flow.flags & FlowFlags.TrueCondition) !== 0;
const nonEvolvingType = finalizeEvolvingArrayType(type);
const narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue);
if (narrowedType === nonEvolvingType) {
return flowType;
}
const incomplete = isIncomplete(flowType);
const resultType = incomplete && narrowedType.flags & TypeFlags.Never ? silentNeverType : narrowedType;
return createFlowType(resultType, incomplete);
}
function getTypeAtSwitchClause(flow: FlowSwitchClause): FlowType {
@@ -8639,7 +8832,7 @@ namespace ts {
seenIncomplete = true;
}
}
return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete);
return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete);
}
function getTypeAtFlowLoopLabel(flow: FlowLabel): FlowType {
@@ -8656,11 +8849,15 @@ namespace ts {
}
// If this flow loop junction and reference are already being processed, return
// the union of the types computed for each branch so far, marked as incomplete.
// We should never see an empty array here because the first antecedent of a loop
// junction is always the non-looping control flow path that leads to the top.
// It is possible to see an empty array in cases where loops are nested and the
// back edge of the outer loop reaches an inner loop that is already being analyzed.
// In such cases we restart the analysis of the inner loop, which will then see
// a non-empty in-process array for the outer loop and eventually terminate because
// the first antecedent of a loop junction is always the non-looping control flow
// path that leads to the top.
for (let i = flowLoopStart; i < flowLoopCount; i++) {
if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) {
return createFlowType(getUnionType(flowLoopTypes[i]), /*incomplete*/ true);
if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) {
return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], /*subtypeReduction*/ false), /*incomplete*/ true);
}
}
// Add the flow loop junction and reference to the in-process stack and analyze
@@ -8704,7 +8901,7 @@ namespace ts {
}
// The result is incomplete if the first antecedent (the non-looping control flow path)
// is incomplete.
const result = getUnionType(antecedentTypes, subtypeReduction);
const result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction);
if (isIncomplete(firstAntecedentType)) {
return createFlowType(result, /*incomplete*/ true);
}
@@ -8804,7 +9001,7 @@ namespace ts {
}
if (assumeTrue) {
const narrowedType = filterType(type, t => areTypesComparable(t, valueType));
return narrowedType.flags & TypeFlags.Never ? type : narrowedType;
return narrowedType.flags & TypeFlags.Never ? type : replacePrimitivesWithLiterals(narrowedType, valueType);
}
if (isUnitType(valueType)) {
const regularType = getRegularTypeOfLiteralType(valueType);
@@ -8851,7 +9048,9 @@ namespace ts {
const clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
const hasDefaultClause = clauseStart === clauseEnd || contains(clauseTypes, neverType);
const discriminantType = getUnionType(clauseTypes);
const caseType = discriminantType.flags & TypeFlags.Never ? neverType : filterType(type, t => isTypeComparableTo(discriminantType, t));
const caseType =
discriminantType.flags & TypeFlags.Never ? neverType :
replacePrimitivesWithLiterals(filterType(type, t => isTypeComparableTo(discriminantType, t)), discriminantType);
if (!hasDefaultClause) {
return caseType;
}
@@ -9084,6 +9283,10 @@ namespace ts {
}
}
function isConstVariable(symbol: Symbol) {
return symbol.flags & SymbolFlags.Variable && (getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Const) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType;
}
function checkIdentifier(node: Identifier): Type {
const symbol = getResolvedSymbol(node);
@@ -9095,7 +9298,7 @@ namespace ts {
// can explicitly bound arguments objects
if (symbol === argumentsSymbol) {
const container = getContainingFunction(node);
if (languageVersion < ScriptTarget.ES6) {
if (languageVersion < ScriptTarget.ES2015) {
if (container.kind === SyntaxKind.ArrowFunction) {
error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
}
@@ -9120,7 +9323,7 @@ namespace ts {
// Due to the emit for class decorators, any reference to the class from inside of the class body
// must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
// behavior of class names in ES6.
if (languageVersion === ScriptTarget.ES6
if (languageVersion === ScriptTarget.ES2015
&& declaration.kind === SyntaxKind.ClassDeclaration
&& nodeIsDecorated(declaration)) {
let container = getContainingClass(node);
@@ -9174,28 +9377,28 @@ namespace ts {
// When the control flow originates in a function expression or arrow function and we are referencing
// a const variable or parameter from an outer function, we extend the origin of the control flow
// analysis to include the immediately enclosing function.
while (flowContainer !== declarationContainer &&
(flowContainer.kind === SyntaxKind.FunctionExpression || flowContainer.kind === SyntaxKind.ArrowFunction) &&
(isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
while (flowContainer !== declarationContainer && (flowContainer.kind === SyntaxKind.FunctionExpression ||
flowContainer.kind === SyntaxKind.ArrowFunction || isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
(isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
flowContainer = getControlFlowContainer(flowContainer);
}
// We only look for uninitialized variables in strict null checking mode, and only when we can analyze
// the entire control flow graph from the variable's declaration (i.e. when the flow container and
// declaration container are the same).
const assumeInitialized = isParameter || isOuterVariable ||
type !== autoType && (!strictNullChecks || (type.flags & TypeFlags.Any) !== 0) ||
type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & TypeFlags.Any) !== 0) ||
isInAmbientContext(declaration);
const flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer);
// A variable is considered uninitialized when it is possible to analyze the entire control flow graph
// from declaration to use, and when the variable's declared type doesn't include undefined but the
// control flow based type does include undefined.
if (type === autoType) {
if (flowType === autoType) {
if (type === autoType || type === autoArrayType) {
if (flowType === autoType || flowType === autoArrayType) {
if (compilerOptions.noImplicitAny) {
error(declaration.name, Diagnostics.Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol));
error(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(anyType));
error(declaration.name, Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType));
error(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
}
return anyType;
return convertAutoToAny(flowType);
}
}
else if (!assumeInitialized && !(getFalsyFlags(type) & TypeFlags.Undefined) && getFalsyFlags(flowType) & TypeFlags.Undefined) {
@@ -9219,7 +9422,7 @@ namespace ts {
}
function checkNestedBlockScopedBinding(node: Identifier, symbol: Symbol): void {
if (languageVersion >= ScriptTarget.ES6 ||
if (languageVersion >= ScriptTarget.ES2015 ||
(symbol.flags & (SymbolFlags.BlockScopedVariable | SymbolFlags.Class)) === 0 ||
symbol.valueDeclaration.parent.kind === SyntaxKind.CatchClause) {
return;
@@ -9385,7 +9588,7 @@ namespace ts {
container = getThisContainer(container, /* includeArrowFunctions */ false);
// When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code
needToCaptureLexicalThis = (languageVersion < ScriptTarget.ES6);
needToCaptureLexicalThis = (languageVersion < ScriptTarget.ES2015);
}
switch (container.kind) {
@@ -9493,7 +9696,7 @@ namespace ts {
if (!isCallExpression) {
while (container && container.kind === SyntaxKind.ArrowFunction) {
container = getSuperContainer(container, /*stopOnFunctions*/ true);
needToCaptureLexicalThis = languageVersion < ScriptTarget.ES6;
needToCaptureLexicalThis = languageVersion < ScriptTarget.ES2015;
}
}
@@ -9607,7 +9810,7 @@ namespace ts {
}
if (container.parent.kind === SyntaxKind.ObjectLiteralExpression) {
if (languageVersion < ScriptTarget.ES6) {
if (languageVersion < ScriptTarget.ES2015) {
error(node, Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
return unknownType;
}
@@ -9975,7 +10178,7 @@ namespace ts {
const index = indexOf(arrayLiteral.elements, node);
return getTypeOfPropertyOfContextualType(type, "" + index)
|| getIndexTypeOfContextualType(type, IndexKind.Number)
|| (languageVersion >= ScriptTarget.ES6 ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined);
|| (languageVersion >= ScriptTarget.ES2015 ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined);
}
return undefined;
}
@@ -10208,7 +10411,7 @@ namespace ts {
// if there is no index type / iterated type.
const restArrayType = checkExpression((<SpreadElementExpression>e).expression, contextualMapper);
const restElementType = getIndexTypeOfType(restArrayType, IndexKind.Number) ||
(languageVersion >= ScriptTarget.ES6 ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined);
(languageVersion >= ScriptTarget.ES2015 ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined);
if (restElementType) {
elementTypes.push(restElementType);
}
@@ -10640,7 +10843,7 @@ namespace ts {
}
}
return getUnionType(signatures.map(getReturnTypeOfSignature), /*subtypeReduction*/ true);
return getUnionType(map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true);
}
/// e.g. "props" for React.d.ts,
@@ -10690,7 +10893,7 @@ namespace ts {
}
if (elemType.flags & TypeFlags.Union) {
const types = (<UnionOrIntersectionType>elemType).types;
return getUnionType(types.map(type => {
return getUnionType(map(types, type => {
return getResolvedJsxType(node, type, elemClassType);
}), /*subtypeReduction*/ true);
}
@@ -10956,7 +11159,7 @@ namespace ts {
// - In a static member function or static member accessor
// where this references the constructor function object of a derived class,
// a super property access is permitted and must specify a public static member function of the base class.
if (languageVersion < ScriptTarget.ES6 && getDeclarationKindFromSymbol(prop) !== SyntaxKind.MethodDeclaration) {
if (languageVersion < ScriptTarget.ES2015 && getDeclarationKindFromSymbol(prop) !== SyntaxKind.MethodDeclaration) {
// `prop` refers to a *property* declared in the super class
// rather than a *method*, so it does not satisfy the above criteria.
@@ -14278,7 +14481,7 @@ namespace ts {
}
if (node.type) {
if (languageVersion >= ScriptTarget.ES6 && isSyntacticallyValidGenerator(node)) {
if (languageVersion >= ScriptTarget.ES2015 && isSyntacticallyValidGenerator(node)) {
const returnType = getTypeFromTypeNode(node.type);
if (returnType === voidType) {
error(node.type, Diagnostics.A_generator_cannot_have_a_void_type_annotation);
@@ -15239,7 +15442,7 @@ namespace ts {
* callable `then` signature.
*/
function checkAsyncFunctionReturnType(node: FunctionLikeDeclaration): Type {
if (languageVersion >= ScriptTarget.ES6) {
if (languageVersion >= ScriptTarget.ES2015) {
const returnType = getTypeFromTypeNode(node.type);
return checkCorrectPromiseType(returnType, node.type, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type);
}
@@ -15766,7 +15969,7 @@ namespace ts {
function checkCollisionWithRequireExportsInGeneratedCode(node: Node, name: Identifier) {
// No need to check for require or exports for ES6 modules and later
if (modulekind >= ModuleKind.ES6) {
if (modulekind >= ModuleKind.ES2015) {
return;
}
@@ -15947,7 +16150,7 @@ namespace ts {
}
function convertAutoToAny(type: Type) {
return type === autoType ? anyType : type;
return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
}
// Check variable, parameter, or property declaration
@@ -16262,7 +16465,7 @@ namespace ts {
if (isTypeAny(inputType)) {
return inputType;
}
if (languageVersion >= ScriptTarget.ES6) {
if (languageVersion >= ScriptTarget.ES2015) {
return checkElementTypeOfIterable(inputType, errorNode);
}
if (allowStringInput) {
@@ -16440,7 +16643,7 @@ namespace ts {
* 2. Some constituent is a string and target is less than ES5 (because in ES3 string is not indexable).
*/
function checkElementTypeOfArrayOrString(arrayOrStringType: Type, errorNode: Node): Type {
Debug.assert(languageVersion < ScriptTarget.ES6);
Debug.assert(languageVersion < ScriptTarget.ES2015);
// After we remove all types that are StringLike, we will know if there was a string constituent
// based on whether the remaining type is the same as the initial type.
@@ -17750,7 +17953,7 @@ namespace ts {
}
}
else {
if (modulekind === ModuleKind.ES6 && !isInAmbientContext(node)) {
if (modulekind === ModuleKind.ES2015 && !isInAmbientContext(node)) {
// Import equals declaration is deprecated in es6 or above
grammarErrorOnNode(node, Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead);
}
@@ -17838,7 +18041,7 @@ namespace ts {
checkExternalModuleExports(container);
if (node.isExportEquals && !isInAmbientContext(node)) {
if (modulekind === ModuleKind.ES6) {
if (modulekind === ModuleKind.ES2015) {
// export assignment is not supported in es6 modules
grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead);
}
@@ -17866,7 +18069,7 @@ namespace ts {
}
// Checks for export * conflicts
const exports = getExportsOfModule(moduleSymbol);
exports.forEach(({ declarations, flags }, id) => {
exports && exports.forEach(({ declarations, flags }, id) => {
if (id === "__export") {
return;
}
@@ -17893,7 +18096,8 @@ namespace ts {
}
function isNotOverload(declaration: Declaration): boolean {
return declaration.kind !== SyntaxKind.FunctionDeclaration || !!(declaration as FunctionDeclaration).body;
return (declaration.kind !== SyntaxKind.FunctionDeclaration && declaration.kind !== SyntaxKind.MethodDeclaration) ||
!!(declaration as FunctionDeclaration).body;
}
}
@@ -19343,7 +19547,7 @@ namespace ts {
getGlobalTemplateStringsArrayType = memoize(() => getGlobalType("TemplateStringsArray"));
if (languageVersion >= ScriptTarget.ES6) {
if (languageVersion >= ScriptTarget.ES2015) {
getGlobalESSymbolType = memoize(() => getGlobalType("Symbol"));
getGlobalIterableType = memoize(() => <GenericType>getGlobalType("Iterable", /*arity*/ 1));
getGlobalIteratorType = memoize(() => <GenericType>getGlobalType("Iterator", /*arity*/ 1));
@@ -19357,6 +19561,7 @@ namespace ts {
}
anyArrayType = createArrayType(anyType);
autoArrayType = createArrayType(autoType);
const symbol = getGlobalSymbol("ReadonlyArray", SymbolFlags.Type, /*diagnostic*/ undefined);
globalReadonlyArrayType = symbol && <GenericType>getTypeOfGlobalSymbol(symbol, /*arity*/ 1);
@@ -19376,7 +19581,7 @@ namespace ts {
// If we found the module, report errors if it does not have the necessary exports.
if (helpersModule) {
const exports = helpersModule.exports;
if (requestedExternalEmitHelpers & NodeFlags.HasClassExtends && languageVersion < ScriptTarget.ES6) {
if (requestedExternalEmitHelpers & NodeFlags.HasClassExtends && languageVersion < ScriptTarget.ES2015) {
verifyHelperSymbol(exports, "__extends", SymbolFlags.Value);
}
if (requestedExternalEmitHelpers & NodeFlags.HasJsxSpreadAttributes && compilerOptions.jsx !== JsxEmit.Preserve) {
@@ -19393,7 +19598,7 @@ namespace ts {
}
if (requestedExternalEmitHelpers & NodeFlags.HasAsyncFunctions) {
verifyHelperSymbol(exports, "__awaiter", SymbolFlags.Value);
if (languageVersion < ScriptTarget.ES6) {
if (languageVersion < ScriptTarget.ES2015) {
verifyHelperSymbol(exports, "__generator", SymbolFlags.Value);
}
}
@@ -19970,7 +20175,7 @@ namespace ts {
if (!node.body) {
return grammarErrorOnNode(node.asteriskToken, Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
}
if (languageVersion < ScriptTarget.ES6) {
if (languageVersion < ScriptTarget.ES2015) {
return grammarErrorOnNode(node.asteriskToken, Diagnostics.Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher);
}
}
+9 -2
View File
@@ -101,7 +101,7 @@ namespace ts {
"amd": ModuleKind.AMD,
"system": ModuleKind.System,
"umd": ModuleKind.UMD,
"es6": ModuleKind.ES6,
"es6": ModuleKind.ES2015,
"es2015": ModuleKind.ES2015,
}),
description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015,
@@ -261,8 +261,10 @@ namespace ts {
type: mapOfMapLike({
"es3": ScriptTarget.ES3,
"es5": ScriptTarget.ES5,
"es6": ScriptTarget.ES6,
"es6": ScriptTarget.ES2015,
"es2015": ScriptTarget.ES2015,
"es2016": ScriptTarget.ES2016,
"es2017": ScriptTarget.ES2017,
}),
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015,
paramType: Diagnostics.VERSION,
@@ -444,6 +446,11 @@ namespace ts {
name: "importHelpers",
type: "boolean",
description: Diagnostics.Import_emit_helpers_from_tslib
},
{
name: "alwaysStrict",
type: "boolean",
description: Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
}
];
+39 -4
View File
@@ -19,6 +19,9 @@ namespace ts {
True = -1
}
// More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times.
export const collator: { compare(a: string, b: string): number } = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined;
export function createFileMap<T>(keyMapper?: (key: string) => string): FileMap<T> {
const files = new StringMap<T>();
return {
@@ -240,13 +243,33 @@ namespace ts {
if (array) {
result = [];
for (let i = 0; i < array.length; i++) {
const v = array[i];
result.push(f(v, i));
result.push(f(array[i], i));
}
}
return result;
}
// Maps from T to T and avoids allocation if all elements map to themselves
export function sameMap<T>(array: T[], f: (x: T, i: number) => T): T[] {
let result: T[];
if (array) {
for (let i = 0; i < array.length; i++) {
if (result) {
result.push(f(array[i], i));
}
else {
const item = array[i];
const mapped = f(item, i);
if (item !== mapped) {
result = array.slice(0, i);
result.push(mapped);
}
}
}
}
return result || array;
}
/**
* Flattens an array containing a mix of array or non-array elements.
*
@@ -374,6 +397,17 @@ namespace ts {
return result;
}
export function some<T>(array: T[], predicate?: (value: T) => boolean): boolean {
if (array) {
for (const v of array) {
if (!predicate || predicate(v)) {
return true;
}
}
}
return false;
}
export function concatenate<T>(array1: T[], array2: T[]): T[] {
if (!array2 || !array2.length) return array1;
if (!array1 || !array1.length) return array2;
@@ -755,7 +789,8 @@ namespace ts {
if (a === undefined) return Comparison.LessThan;
if (b === undefined) return Comparison.GreaterThan;
if (ignoreCase) {
if (String.prototype.localeCompare) {
if (collator && String.prototype.localeCompare) {
// accent means a ≠ b, a ≠ á, a = A
const result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" });
return result < 0 ? Comparison.LessThan : result > 0 ? Comparison.GreaterThan : Comparison.EqualTo;
}
@@ -942,7 +977,7 @@ namespace ts {
export function getEmitModuleKind(compilerOptions: CompilerOptions) {
return typeof compilerOptions.module === "number" ?
compilerOptions.module :
getEmitScriptTarget(compilerOptions) === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.CommonJS;
getEmitScriptTarget(compilerOptions) >= ScriptTarget.ES2015 ? ModuleKind.ES2015 : ModuleKind.CommonJS;
}
/* @internal */
+6 -2
View File
@@ -1923,7 +1923,7 @@
"category": "Error",
"code": 2685
},
"Identifier '{0}' must be imported from a module": {
"'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead.": {
"category": "Error",
"code": 2686
},
@@ -2861,6 +2861,10 @@
"category": "Error",
"code": 6140
},
"Parse in strict mode and emit \"use strict\" for each source file": {
"category": "Message",
"code": 6141
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7005
@@ -2957,7 +2961,7 @@
"category": "Error",
"code": 7033
},
"Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined.": {
"Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined.": {
"category": "Error",
"code": 7034
},
+24 -4
View File
@@ -504,15 +504,29 @@ const _super = (function (geti, seti) {
// Contextual keywords
case SyntaxKind.AbstractKeyword:
case SyntaxKind.AsKeyword:
case SyntaxKind.AnyKeyword:
case SyntaxKind.AsyncKeyword:
case SyntaxKind.AwaitKeyword:
case SyntaxKind.BooleanKeyword:
case SyntaxKind.ConstructorKeyword:
case SyntaxKind.DeclareKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.GetKeyword:
case SyntaxKind.IsKeyword:
case SyntaxKind.ModuleKeyword:
case SyntaxKind.NamespaceKeyword:
case SyntaxKind.NeverKeyword:
case SyntaxKind.ReadonlyKeyword:
case SyntaxKind.RequireKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.SetKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.TypeKeyword:
case SyntaxKind.UndefinedKeyword:
case SyntaxKind.FromKeyword:
case SyntaxKind.GlobalKeyword:
case SyntaxKind.OfKeyword:
writeTokenText(kind);
return;
@@ -1198,12 +1212,14 @@ const _super = (function (geti, seti) {
function emitCallExpression(node: CallExpression) {
emitExpression(node.expression);
emitTypeArguments(node, node.typeArguments);
emitExpressionList(node, node.arguments, ListFormat.CallExpressionArguments);
}
function emitNewExpression(node: NewExpression) {
write("new ");
emitExpression(node.expression);
emitTypeArguments(node, node.typeArguments);
emitExpressionList(node, node.arguments, ListFormat.NewExpressionArguments);
}
@@ -1575,6 +1591,7 @@ const _super = (function (geti, seti) {
function emitVariableDeclaration(node: VariableDeclaration) {
emit(node.name);
emitWithPrefix(": ", node.type);
emitExpressionWithPrefix(" = ", node.initializer);
}
@@ -2165,7 +2182,7 @@ const _super = (function (geti, seti) {
// Only Emit __extends function when target ES5.
// For target ES6 and above, we can emit classDeclaration as is.
if ((languageVersion < ScriptTarget.ES6) && (!extendsEmitted && node.flags & NodeFlags.HasClassExtends)) {
if ((languageVersion < ScriptTarget.ES2015) && (!extendsEmitted && node.flags & NodeFlags.HasClassExtends)) {
writeLines(extendsHelper);
extendsEmitted = true;
helpersEmitted = true;
@@ -2192,9 +2209,12 @@ const _super = (function (geti, seti) {
helpersEmitted = true;
}
if (!awaiterEmitted && node.flags & NodeFlags.HasAsyncFunctions) {
// Only emit __awaiter function when target ES5/ES6.
// Only emit __generator function when target ES5.
// For target ES2017 and above, we can emit async/await as is.
if ((languageVersion < ScriptTarget.ES2017) && (!awaiterEmitted && node.flags & NodeFlags.HasAsyncFunctions)) {
writeLines(awaiterHelper);
if (languageVersion < ScriptTarget.ES6) {
if (languageVersion < ScriptTarget.ES2015) {
writeLines(generatorHelper);
}
+54 -18
View File
@@ -525,9 +525,9 @@ namespace ts {
return node;
}
export function createFunctionExpression(asteriskToken: AsteriskToken, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags) {
export function createFunctionExpression(modifiers: Modifier[], asteriskToken: AsteriskToken, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags) {
const node = <FunctionExpression>createNode(SyntaxKind.FunctionExpression, location, flags);
node.modifiers = undefined;
node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
node.asteriskToken = asteriskToken;
node.name = typeof name === "string" ? createIdentifier(name) : name;
node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined;
@@ -537,9 +537,9 @@ namespace ts {
return node;
}
export function updateFunctionExpression(node: FunctionExpression, name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block) {
if (node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) {
return updateNode(createFunctionExpression(node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node);
export function updateFunctionExpression(node: FunctionExpression, modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block) {
if (node.name !== name || node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) {
return updateNode(createFunctionExpression(modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node);
}
return node;
}
@@ -1736,6 +1736,7 @@ namespace ts {
export function createAwaiterHelper(externalHelpersModuleName: Identifier | undefined, hasLexicalArguments: boolean, promiseConstructor: EntityName | Expression, body: Block) {
const generatorFunc = createFunctionExpression(
/*modifiers*/ undefined,
createToken(SyntaxKind.AsteriskToken),
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -1909,6 +1910,7 @@ namespace ts {
createCall(
createParen(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -1984,7 +1986,7 @@ namespace ts {
}
else if (callee.kind === SyntaxKind.SuperKeyword) {
thisArg = createThis();
target = languageVersion < ScriptTarget.ES6 ? createIdentifier("_super", /*location*/ callee) : <PrimaryExpression>callee;
target = languageVersion < ScriptTarget.ES2015 ? createIdentifier("_super", /*location*/ callee) : <PrimaryExpression>callee;
}
else {
switch (callee.kind) {
@@ -2090,6 +2092,7 @@ namespace ts {
const properties: ObjectLiteralElementLike[] = [];
if (getAccessor) {
const getterFunction = createFunctionExpression(
getAccessor.modifiers,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -2105,6 +2108,7 @@ namespace ts {
if (setAccessor) {
const setterFunction = createFunctionExpression(
setAccessor.modifiers,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -2171,6 +2175,7 @@ namespace ts {
createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name),
setOriginalNode(
createFunctionExpression(
method.modifiers,
method.asteriskToken,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -2206,7 +2211,7 @@ namespace ts {
* @param visitor: Optional callback used to visit any custom prologue directives.
*/
export function addPrologueDirectives(target: Statement[], source: Statement[], ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult<Node>): number {
Debug.assert(target.length === 0, "PrologueDirectives should be at the first statement in the target statements array");
Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
let foundUseStrict = false;
let statementOffset = 0;
const numStatements = source.length;
@@ -2219,22 +2224,53 @@ namespace ts {
target.push(statement);
}
else {
if (ensureUseStrict && !foundUseStrict) {
target.push(startOnNewLine(createStatement(createLiteral("use strict"))));
foundUseStrict = true;
}
if (getEmitFlags(statement) & EmitFlags.CustomPrologue) {
target.push(visitor ? visitNode(statement, visitor, isStatement) : statement);
}
else {
break;
}
break;
}
statementOffset++;
}
if (ensureUseStrict && !foundUseStrict) {
target.push(startOnNewLine(createStatement(createLiteral("use strict"))));
}
while (statementOffset < numStatements) {
const statement = source[statementOffset];
if (getEmitFlags(statement) & EmitFlags.CustomPrologue) {
target.push(visitor ? visitNode(statement, visitor, isStatement) : statement);
}
else {
break;
}
statementOffset++;
}
return statementOffset;
}
/**
* Ensures "use strict" directive is added
*
* @param node source file
*/
export function ensureUseStrict(node: SourceFile): SourceFile {
let foundUseStrict = false;
for (const statement of node.statements) {
if (isPrologueDirective(statement)) {
if (isUseStrictPrologue(statement as ExpressionStatement)) {
foundUseStrict = true;
break;
}
}
else {
break;
}
}
if (!foundUseStrict) {
const statements: Statement[] = [];
statements.push(startOnNewLine(createStatement(createLiteral("use strict"))));
// add "use strict" as the first statement
return updateSourceFileNode(node, statements.concat(node.statements));
}
return node;
}
/**
* Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
* order of operations.
@@ -2908,4 +2944,4 @@ namespace ts {
function tryGetModuleNameFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration, host: EmitHost, resolver: EmitResolver, compilerOptions: CompilerOptions) {
return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
}
}
}
+6 -2
View File
@@ -1469,12 +1469,16 @@ namespace ts {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"));
}
if (options.noImplicitUseStrict && options.alwaysStrict) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"));
}
const languageVersion = options.target || ScriptTarget.ES3;
const outFile = options.outFile || options.out;
const firstNonAmbientExternalModuleSourceFile = forEach(files, f => isExternalModule(f) && !isDeclarationFile(f) ? f : undefined);
if (options.isolatedModules) {
if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES6) {
if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES2015) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher));
}
@@ -1484,7 +1488,7 @@ namespace ts {
programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided));
}
}
else if (firstNonAmbientExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && options.module === ModuleKind.None) {
else if (firstNonAmbientExternalModuleSourceFile && languageVersion < ScriptTarget.ES2015 && options.module === ModuleKind.None) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
const span = getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
programDiagnostics.add(createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
+1 -1
View File
@@ -1191,7 +1191,7 @@ namespace ts {
}
function scanBinaryOrOctalDigits(base: number): number {
Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8");
Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8");
let value = 0;
// For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
+4
View File
@@ -479,6 +479,10 @@ namespace ts {
// Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
// (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
let options: any;
if (!directoryExists(directoryName)) {
return;
}
if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) {
options = { persistent: true, recursive: !!recursive };
}
+14 -7
View File
@@ -1,17 +1,18 @@
/// <reference path="visitor.ts" />
/// <reference path="transformers/ts.ts" />
/// <reference path="transformers/jsx.ts" />
/// <reference path="transformers/es7.ts" />
/// <reference path="transformers/es6.ts" />
/// <reference path="transformers/es2017.ts" />
/// <reference path="transformers/es2016.ts" />
/// <reference path="transformers/es2015.ts" />
/// <reference path="transformers/generators.ts" />
/// <reference path="transformers/module/module.ts" />
/// <reference path="transformers/module/system.ts" />
/// <reference path="transformers/module/es6.ts" />
/// <reference path="transformers/module/es2015.ts" />
/* @internal */
namespace ts {
const moduleTransformerMap = new NumberMap<ModuleKind, Transformer>([
[ModuleKind.ES6, transformES6Module],
[ModuleKind.ES2015, transformES2015Module],
[ModuleKind.System, transformSystemModule],
[ModuleKind.AMD, transformModule],
[ModuleKind.CommonJS, transformModule],
@@ -115,10 +116,16 @@ namespace ts {
transformers.push(transformJsx);
}
transformers.push(transformES7);
if (languageVersion < ScriptTarget.ES2017) {
transformers.push(transformES2017);
}
if (languageVersion < ScriptTarget.ES6) {
transformers.push(transformES6);
if (languageVersion < ScriptTarget.ES2016) {
transformers.push(transformES2016);
}
if (languageVersion < ScriptTarget.ES2015) {
transformers.push(transformES2015);
transformers.push(transformGenerators);
}
@@ -4,7 +4,7 @@
/*@internal*/
namespace ts {
const enum ES6SubstitutionFlags {
const enum ES2015SubstitutionFlags {
/** Enables substitutions for captured `this` */
CapturedThis = 1 << 0,
/** Enables substitutions for block-scoped bindings. */
@@ -163,7 +163,7 @@ namespace ts {
ReplaceWithReturn,
}
export function transformES6(context: TransformationContext) {
export function transformES2015(context: TransformationContext) {
const {
startLexicalEnvironment,
endLexicalEnvironment,
@@ -197,7 +197,7 @@ namespace ts {
* They are persisted between each SourceFile transformation and should not
* be reset.
*/
let enabledSubstitutions: ES6SubstitutionFlags;
let enabledSubstitutions: ES2015SubstitutionFlags;
return transformSourceFile;
@@ -252,7 +252,7 @@ namespace ts {
}
function shouldCheckNode(node: Node): boolean {
return (node.transformFlags & TransformFlags.ES6) !== 0 ||
return (node.transformFlags & TransformFlags.ES2015) !== 0 ||
node.kind === SyntaxKind.LabeledStatement ||
(isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node));
}
@@ -261,7 +261,7 @@ namespace ts {
if (shouldCheckNode(node)) {
return visitJavaScript(node);
}
else if (node.transformFlags & TransformFlags.ContainsES6) {
else if (node.transformFlags & TransformFlags.ContainsES2015) {
return visitEachChild(node, visitor, context);
}
else {
@@ -681,6 +681,7 @@ namespace ts {
const extendsClauseElement = getClassExtendsHeritageClauseElement(node);
const classFunction = createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -1416,6 +1417,7 @@ namespace ts {
if (getAccessor) {
const getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined);
setSourceMapRange(getterFunction, getSourceMapRange(getAccessor));
setEmitFlags(getterFunction, EmitFlags.NoLeadingComments);
const getter = createPropertyAssignment("get", getterFunction);
setCommentRange(getter, getCommentRange(getAccessor));
properties.push(getter);
@@ -1424,6 +1426,7 @@ namespace ts {
if (setAccessor) {
const setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined);
setSourceMapRange(setterFunction, getSourceMapRange(setAccessor));
setEmitFlags(setterFunction, EmitFlags.NoLeadingComments);
const setter = createPropertyAssignment("set", setterFunction);
setCommentRange(setter, getCommentRange(setAccessor));
properties.push(setter);
@@ -1509,6 +1512,7 @@ namespace ts {
const expression = setOriginalNode(
createFunctionExpression(
/*modifiers*/ undefined,
node.asteriskToken,
name,
/*typeParameters*/ undefined,
@@ -2240,6 +2244,7 @@ namespace ts {
/*type*/ undefined,
setEmitFlags(
createFunctionExpression(
/*modifiers*/ undefined,
isAsyncBlockContainingAwait ? createToken(SyntaxKind.AsteriskToken) : undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -3033,7 +3038,7 @@ namespace ts {
function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void) {
const savedEnclosingFunction = enclosingFunction;
if (enabledSubstitutions & ES6SubstitutionFlags.CapturedThis && isFunctionLike(node)) {
if (enabledSubstitutions & ES2015SubstitutionFlags.CapturedThis && isFunctionLike(node)) {
// If we are tracking a captured `this`, keep track of the enclosing function.
enclosingFunction = node;
}
@@ -3048,8 +3053,8 @@ namespace ts {
* contains block-scoped bindings (e.g. `let` or `const`).
*/
function enableSubstitutionsForBlockScopedBindings() {
if ((enabledSubstitutions & ES6SubstitutionFlags.BlockScopedBindings) === 0) {
enabledSubstitutions |= ES6SubstitutionFlags.BlockScopedBindings;
if ((enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings) === 0) {
enabledSubstitutions |= ES2015SubstitutionFlags.BlockScopedBindings;
context.enableSubstitution(SyntaxKind.Identifier);
}
}
@@ -3059,8 +3064,8 @@ namespace ts {
* contains a captured `this`.
*/
function enableSubstitutionsForCapturedThis() {
if ((enabledSubstitutions & ES6SubstitutionFlags.CapturedThis) === 0) {
enabledSubstitutions |= ES6SubstitutionFlags.CapturedThis;
if ((enabledSubstitutions & ES2015SubstitutionFlags.CapturedThis) === 0) {
enabledSubstitutions |= ES2015SubstitutionFlags.CapturedThis;
context.enableSubstitution(SyntaxKind.ThisKeyword);
context.enableEmitNotification(SyntaxKind.Constructor);
context.enableEmitNotification(SyntaxKind.MethodDeclaration);
@@ -3099,7 +3104,7 @@ namespace ts {
function substituteIdentifier(node: Identifier) {
// Only substitute the identifier if we have enabled substitutions for block-scoped
// bindings.
if (enabledSubstitutions & ES6SubstitutionFlags.BlockScopedBindings) {
if (enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings) {
const original = getParseTreeNode(node, isIdentifier);
if (original && isNameOfDeclarationWithCollidingName(original)) {
return getGeneratedNameForNode(original);
@@ -3152,7 +3157,7 @@ namespace ts {
* @param node An Identifier node.
*/
function substituteExpressionIdentifier(node: Identifier): Identifier {
if (enabledSubstitutions & ES6SubstitutionFlags.BlockScopedBindings) {
if (enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings) {
const declaration = resolver.getReferencedDeclarationWithCollidingName(node);
if (declaration) {
return getGeneratedNameForNode(declaration.name);
@@ -3168,7 +3173,7 @@ namespace ts {
* @param node The ThisKeyword node.
*/
function substituteThisKeyword(node: PrimaryExpression): PrimaryExpression {
if (enabledSubstitutions & ES6SubstitutionFlags.CapturedThis
if (enabledSubstitutions & ES2015SubstitutionFlags.CapturedThis
&& enclosingFunction
&& getEmitFlags(enclosingFunction) & EmitFlags.CapturesThis) {
return createIdentifier("_this", /*location*/ node);
@@ -3255,4 +3260,4 @@ namespace ts {
return isIdentifier(expression) && expression === parameter.name;
}
}
}
}
@@ -3,7 +3,7 @@
/*@internal*/
namespace ts {
export function transformES7(context: TransformationContext) {
export function transformES2016(context: TransformationContext) {
const { hoistVariableDeclaration } = context;
return transformSourceFile;
@@ -17,10 +17,10 @@ namespace ts {
}
function visitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.ES7) {
if (node.transformFlags & TransformFlags.ES2016) {
return visitorWorker(node);
}
else if (node.transformFlags & TransformFlags.ContainsES7) {
else if (node.transformFlags & TransformFlags.ContainsES2016) {
return visitEachChild(node, visitor, context);
}
else {
@@ -40,7 +40,7 @@ namespace ts {
}
function visitBinaryExpression(node: BinaryExpression): Expression {
// We are here because ES7 adds support for the exponentiation operator.
// We are here because ES2016 adds support for the exponentiation operator.
const left = visitNode(node.left, visitor, isExpression);
const right = visitNode(node.right, visitor, isExpression);
if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskEqualsToken) {
@@ -98,4 +98,4 @@ namespace ts {
}
}
}
}
}
+510
View File
@@ -0,0 +1,510 @@
/// <reference path="../factory.ts" />
/// <reference path="../visitor.ts" />
/*@internal*/
namespace ts {
type SuperContainer = ClassDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration;
export function transformES2017(context: TransformationContext) {
const enum ES2017SubstitutionFlags {
/** Enables substitutions for async methods with `super` calls. */
AsyncMethodsWithSuper = 1 << 0
}
const {
startLexicalEnvironment,
endLexicalEnvironment,
} = context;
const resolver = context.getEmitResolver();
const compilerOptions = context.getCompilerOptions();
const languageVersion = getEmitScriptTarget(compilerOptions);
// These variables contain state that changes as we descend into the tree.
let currentSourceFileExternalHelpersModuleName: Identifier;
/**
* Keeps track of whether expression substitution has been enabled for specific edge cases.
* They are persisted between each SourceFile transformation and should not be reset.
*/
let enabledSubstitutions: ES2017SubstitutionFlags;
/**
* Keeps track of whether we are within any containing namespaces when performing
* just-in-time substitution while printing an expression identifier.
*/
let applicableSubstitutions: ES2017SubstitutionFlags;
/**
* This keeps track of containers where `super` is valid, for use with
* just-in-time substitution for `super` expressions inside of async methods.
*/
let currentSuperContainer: SuperContainer;
// Save the previous transformation hooks.
const previousOnEmitNode = context.onEmitNode;
const previousOnSubstituteNode = context.onSubstituteNode;
// Set new transformation hooks.
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
let currentScope: SourceFile | Block | ModuleBlock | CaseBlock;
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)) {
return node;
}
currentSourceFileExternalHelpersModuleName = node.externalHelpersModuleName;
return visitEachChild(node, visitor, context);
}
function visitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.ES2017) {
return visitorWorker(node);
}
else if (node.transformFlags & TransformFlags.ContainsES2017) {
return visitEachChild(node, visitor, context);
}
return node;
}
function visitorWorker(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.AsyncKeyword:
// ES2017 async modifier should be elided for targets < ES2017
return undefined;
case SyntaxKind.AwaitExpression:
// ES2017 'await' expressions must be transformed for targets < ES2017.
return visitAwaitExpression(<AwaitExpression>node);
case SyntaxKind.MethodDeclaration:
// ES2017 method declarations may be 'async'
return visitMethodDeclaration(<MethodDeclaration>node);
case SyntaxKind.FunctionDeclaration:
// ES2017 function declarations may be 'async'
return visitFunctionDeclaration(<FunctionDeclaration>node);
case SyntaxKind.FunctionExpression:
// ES2017 function expressions may be 'async'
return visitFunctionExpression(<FunctionExpression>node);
case SyntaxKind.ArrowFunction:
// ES2017 arrow functions may be 'async'
return visitArrowFunction(<ArrowFunction>node);
default:
Debug.failBadSyntaxKind(node);
return node;
}
}
/**
* Visits an await expression.
*
* This function will be called any time a ES2017 await expression is encountered.
*
* @param node The await expression node.
*/
function visitAwaitExpression(node: AwaitExpression): Expression {
return setOriginalNode(
createYield(
/*asteriskToken*/ undefined,
visitNode(node.expression, visitor, isExpression),
/*location*/ node
),
node
);
}
/**
* Visits a method declaration of a class.
*
* This function will be called when one of the following conditions are met:
* - The node is marked as async
*
* @param node The method node.
*/
function visitMethodDeclaration(node: MethodDeclaration) {
if (!isAsyncFunctionLike(node)) {
return node;
}
const method = createMethod(
/*decorators*/ undefined,
visitNodes(node.modifiers, visitor, isModifier),
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
/*type*/ undefined,
transformFunctionBody(node),
/*location*/ 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.
setCommentRange(method, node);
setSourceMapRange(method, moveRangePastDecorators(node));
setOriginalNode(method, node);
return method;
}
/**
* Visits a function declaration.
*
* This function will be called when one of the following conditions are met:
* - The node is marked async
*
* @param node The function node.
*/
function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult<Statement> {
if (!isAsyncFunctionLike(node)) {
return node;
}
const func = createFunctionDeclaration(
/*decorators*/ undefined,
visitNodes(node.modifiers, visitor, isModifier),
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
/*type*/ undefined,
transformFunctionBody(node),
/*location*/ node
);
setOriginalNode(func, node);
return func;
}
/**
* Visits a function expression node.
*
* This function will be called when one of the following conditions are met:
* - The node is marked async
*
* @param node The function expression node.
*/
function visitFunctionExpression(node: FunctionExpression): Expression {
if (!isAsyncFunctionLike(node)) {
return node;
}
if (nodeIsMissing(node.body)) {
return createOmittedExpression();
}
const func = createFunctionExpression(
/*modifiers*/ undefined,
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
/*type*/ undefined,
transformFunctionBody(node),
/*location*/ node
);
setOriginalNode(func, node);
return func;
}
/**
* @remarks
* This function will be called when one of the following conditions are met:
* - The node is marked async
*/
function visitArrowFunction(node: ArrowFunction) {
if (!isAsyncFunctionLike(node)) {
return node;
}
const func = createArrowFunction(
visitNodes(node.modifiers, visitor, isModifier),
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
/*type*/ undefined,
node.equalsGreaterThanToken,
transformConciseBody(node),
/*location*/ node
);
setOriginalNode(func, node);
return func;
}
function transformFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody {
return <FunctionBody>transformAsyncFunctionBody(node);
}
function transformConciseBody(node: ArrowFunction): ConciseBody {
return transformAsyncFunctionBody(node);
}
function transformFunctionBodyWorker(body: Block, start = 0) {
const savedCurrentScope = currentScope;
currentScope = body;
startLexicalEnvironment();
const statements = visitNodes(body.statements, visitor, isStatement, start);
const visited = updateBlock(body, statements);
const declarations = endLexicalEnvironment();
currentScope = savedCurrentScope;
return mergeFunctionBodyLexicalEnvironment(visited, declarations);
}
function transformAsyncFunctionBody(node: FunctionLikeDeclaration): ConciseBody | FunctionBody {
const nodeType = node.original ? (<FunctionLikeDeclaration>node.original).type : node.type;
const promiseConstructor = languageVersion < ScriptTarget.ES2015 ? getPromiseConstructor(nodeType) : undefined;
const isArrowFunction = node.kind === SyntaxKind.ArrowFunction;
const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0;
// An async function is emit as an outer function that calls an inner
// generator function. To preserve lexical bindings, we pass the current
// `this` and `arguments` objects to `__awaiter`. The generator function
// passed to `__awaiter` is executed inside of the callback to the
// promise constructor.
if (!isArrowFunction) {
const statements: Statement[] = [];
const statementOffset = addPrologueDirectives(statements, (<Block>node.body).statements, /*ensureUseStrict*/ false, visitor);
statements.push(
createReturn(
createAwaiterHelper(
currentSourceFileExternalHelpersModuleName,
hasLexicalArguments,
promiseConstructor,
transformFunctionBodyWorker(<Block>node.body, statementOffset)
)
)
);
const block = createBlock(statements, /*location*/ node.body, /*multiLine*/ true);
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
if (languageVersion >= ScriptTarget.ES2015) {
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) {
enableSubstitutionForAsyncMethodsWithSuper();
setEmitFlags(block, EmitFlags.EmitAdvancedSuperHelper);
}
else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuper) {
enableSubstitutionForAsyncMethodsWithSuper();
setEmitFlags(block, EmitFlags.EmitSuperHelper);
}
}
return block;
}
else {
return createAwaiterHelper(
currentSourceFileExternalHelpersModuleName,
hasLexicalArguments,
promiseConstructor,
<Block>transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ true)
);
}
}
function transformConciseBodyWorker(body: Block | Expression, forceBlockFunctionBody: boolean) {
if (isBlock(body)) {
return transformFunctionBodyWorker(body);
}
else {
startLexicalEnvironment();
const visited: Expression | Block = visitNode(body, visitor, isConciseBody);
const declarations = endLexicalEnvironment();
const merged = mergeFunctionBodyLexicalEnvironment(visited, declarations);
if (forceBlockFunctionBody && !isBlock(merged)) {
return createBlock([
createReturn(<Expression>merged)
]);
}
else {
return merged;
}
}
}
function getPromiseConstructor(type: TypeNode) {
const typeName = getEntityNameFromTypeNode(type);
if (typeName && isEntityName(typeName)) {
const serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
if (serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
|| serializationKind === TypeReferenceSerializationKind.Unknown) {
return typeName;
}
}
return undefined;
}
function enableSubstitutionForAsyncMethodsWithSuper() {
if ((enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper) === 0) {
enabledSubstitutions |= ES2017SubstitutionFlags.AsyncMethodsWithSuper;
// We need to enable substitutions for call, property access, and element access
// if we need to rewrite super calls.
context.enableSubstitution(SyntaxKind.CallExpression);
context.enableSubstitution(SyntaxKind.PropertyAccessExpression);
context.enableSubstitution(SyntaxKind.ElementAccessExpression);
// We need to be notified when entering and exiting declarations that bind super.
context.enableEmitNotification(SyntaxKind.ClassDeclaration);
context.enableEmitNotification(SyntaxKind.MethodDeclaration);
context.enableEmitNotification(SyntaxKind.GetAccessor);
context.enableEmitNotification(SyntaxKind.SetAccessor);
context.enableEmitNotification(SyntaxKind.Constructor);
}
}
function substituteExpression(node: Expression) {
switch (node.kind) {
case SyntaxKind.PropertyAccessExpression:
return substitutePropertyAccessExpression(<PropertyAccessExpression>node);
case SyntaxKind.ElementAccessExpression:
return substituteElementAccessExpression(<ElementAccessExpression>node);
case SyntaxKind.CallExpression:
if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper) {
return substituteCallExpression(<CallExpression>node);
}
break;
}
return node;
}
function substitutePropertyAccessExpression(node: PropertyAccessExpression) {
if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) {
const flags = getSuperContainerAsyncMethodFlags();
if (flags) {
return createSuperAccessInAsyncMethod(
createLiteral(node.name.text),
flags,
node
);
}
}
return node;
}
function substituteElementAccessExpression(node: ElementAccessExpression) {
if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) {
const flags = getSuperContainerAsyncMethodFlags();
if (flags) {
return createSuperAccessInAsyncMethod(
node.argumentExpression,
flags,
node
);
}
}
return node;
}
function substituteCallExpression(node: CallExpression): Expression {
const expression = node.expression;
if (isSuperProperty(expression)) {
const flags = getSuperContainerAsyncMethodFlags();
if (flags) {
const argumentExpression = isPropertyAccessExpression(expression)
? substitutePropertyAccessExpression(expression)
: substituteElementAccessExpression(expression);
return createCall(
createPropertyAccess(argumentExpression, "call"),
/*typeArguments*/ undefined,
[
createThis(),
...node.arguments
]
);
}
}
return node;
}
function isSuperContainer(node: Node): node is SuperContainer {
const kind = node.kind;
return kind === SyntaxKind.ClassDeclaration
|| kind === SyntaxKind.Constructor
|| kind === SyntaxKind.MethodDeclaration
|| kind === SyntaxKind.GetAccessor
|| kind === SyntaxKind.SetAccessor;
}
/**
* Hook for node emit.
*
* @param node The node to emit.
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void {
const savedApplicableSubstitutions = applicableSubstitutions;
const savedCurrentSuperContainer = currentSuperContainer;
// If we need to support substitutions for `super` in an async method,
// we should track it here.
if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && isSuperContainer(node)) {
currentSuperContainer = node;
}
previousOnEmitNode(emitContext, node, emitCallback);
applicableSubstitutions = savedApplicableSubstitutions;
currentSuperContainer = savedCurrentSuperContainer;
}
/**
* Hooks node substitutions.
*
* @param node The node to substitute.
* @param isExpression A value indicating whether the node is to be used in an expression
* position.
*/
function onSubstituteNode(emitContext: EmitContext, node: Node) {
node = previousOnSubstituteNode(emitContext, node);
if (emitContext === EmitContext.Expression) {
return substituteExpression(<Expression>node);
}
return node;
}
function createSuperAccessInAsyncMethod(argumentExpression: Expression, flags: NodeCheckFlags, location: TextRange): LeftHandSideExpression {
if (flags & NodeCheckFlags.AsyncMethodWithSuperBinding) {
return createPropertyAccess(
createCall(
createIdentifier("_super"),
/*typeArguments*/ undefined,
[argumentExpression]
),
"value",
location
);
}
else {
return createCall(
createIdentifier("_super"),
/*typeArguments*/ undefined,
[argumentExpression],
location
);
}
}
function getSuperContainerAsyncMethodFlags() {
return currentSuperContainer !== undefined
&& resolver.getNodeCheckFlags(currentSuperContainer) & (NodeCheckFlags.AsyncMethodWithSuper | NodeCheckFlags.AsyncMethodWithSuperBinding);
}
}
}
+3 -1
View File
@@ -496,6 +496,7 @@ namespace ts {
if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) {
node = setOriginalNode(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
node.name,
/*typeParameters*/ undefined,
@@ -2591,6 +2592,7 @@ namespace ts {
createThis(),
setEmitFlags(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -3080,4 +3082,4 @@ namespace ts {
);
}
}
}
}
@@ -0,0 +1,43 @@
/// <reference path="../../factory.ts" />
/// <reference path="../../visitor.ts" />
/*@internal*/
namespace ts {
export function transformES2015Module(context: TransformationContext) {
const compilerOptions = context.getCompilerOptions();
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)) {
return node;
}
if (isExternalModule(node) || compilerOptions.isolatedModules) {
return visitEachChild(node, visitor, context);
}
return node;
}
function visitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(<ExportAssignment>node);
}
return node;
}
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult<ImportEqualsDeclaration> {
// Elide `import=` as it is not legal with --module ES6
return undefined;
}
function visitExportAssignment(node: ExportAssignment): VisitResult<ExportAssignment> {
// Elide `export=` as it is not legal with --module ES6
return node.isExportEquals ? undefined : node;
}
}
}
-144
View File
@@ -1,144 +0,0 @@
/// <reference path="../../factory.ts" />
/// <reference path="../../visitor.ts" />
/*@internal*/
namespace ts {
export function transformES6Module(context: TransformationContext) {
const compilerOptions = context.getCompilerOptions();
const resolver = context.getEmitResolver();
let currentSourceFile: SourceFile;
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)) {
return node;
}
if (isExternalModule(node) || compilerOptions.isolatedModules) {
currentSourceFile = node;
return visitEachChild(node, visitor, context);
}
return node;
}
function visitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(<ImportDeclaration>node);
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
case SyntaxKind.ImportClause:
return visitImportClause(<ImportClause>node);
case SyntaxKind.NamedImports:
case SyntaxKind.NamespaceImport:
return visitNamedBindings(<NamedImportBindings>node);
case SyntaxKind.ImportSpecifier:
return visitImportSpecifier(<ImportSpecifier>node);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(<ExportAssignment>node);
case SyntaxKind.ExportDeclaration:
return visitExportDeclaration(<ExportDeclaration>node);
case SyntaxKind.NamedExports:
return visitNamedExports(<NamedExports>node);
case SyntaxKind.ExportSpecifier:
return visitExportSpecifier(<ExportSpecifier>node);
}
return node;
}
function visitExportAssignment(node: ExportAssignment): ExportAssignment {
if (node.isExportEquals) {
return undefined; // do not emit export equals for ES6
}
const original = getOriginalNode(node);
return nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined;
}
function visitExportDeclaration(node: ExportDeclaration): ExportDeclaration {
if (!node.exportClause) {
return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined;
}
if (!resolver.isValueAliasDeclaration(node)) {
return undefined;
}
const newExportClause = visitNode(node.exportClause, visitor, isNamedExports, /*optional*/ true);
if (node.exportClause === newExportClause) {
return node;
}
return newExportClause
? createExportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
newExportClause,
node.moduleSpecifier)
: undefined;
}
function visitNamedExports(node: NamedExports): NamedExports {
const newExports = visitNodes(node.elements, visitor, isExportSpecifier);
if (node.elements === newExports) {
return node;
}
return newExports.length ? createNamedExports(newExports) : undefined;
}
function visitExportSpecifier(node: ExportSpecifier): ExportSpecifier {
return resolver.isValueAliasDeclaration(node) ? node : undefined;
}
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): ImportEqualsDeclaration {
return !isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
function visitImportDeclaration(node: ImportDeclaration) {
if (node.importClause) {
const newImportClause = visitNode(node.importClause, visitor, isImportClause);
if (!newImportClause.name && !newImportClause.namedBindings) {
return undefined;
}
else if (newImportClause !== node.importClause) {
return createImportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
newImportClause,
node.moduleSpecifier);
}
}
return node;
}
function visitImportClause(node: ImportClause): ImportClause {
let newDefaultImport = node.name;
if (!resolver.isReferencedAliasDeclaration(node)) {
newDefaultImport = undefined;
}
const newNamedBindings = visitNode(node.namedBindings, visitor, isNamedImportBindings, /*optional*/ true);
return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings
? createImportClause(newDefaultImport, newNamedBindings)
: node;
}
function visitNamedBindings(node: NamedImportBindings): VisitResult<NamedImportBindings> {
if (node.kind === SyntaxKind.NamespaceImport) {
return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
else {
const newNamedImportElements = visitNodes((<NamedImports>node).elements, visitor, isImportSpecifier);
if (!newNamedImportElements || newNamedImportElements.length == 0) {
return undefined;
}
if (newNamedImportElements === (<NamedImports>node).elements) {
return node;
}
return createNamedImports(newNamedImportElements);
}
}
function visitImportSpecifier(node: ImportSpecifier) {
return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
}
}
+25 -25
View File
@@ -59,7 +59,7 @@ namespace ts {
currentSourceFile = node;
// Collect information about the external module.
({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node, resolver));
({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node));
// Perform the transformation.
const transformModule = transformModuleDelegates.get(moduleKind) || transformModuleDelegates.get(ModuleKind.None);
@@ -179,6 +179,7 @@ namespace ts {
//
// function (require, exports, module1, module2) ...
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -228,7 +229,7 @@ namespace ts {
}
function addExportEqualsIfNeeded(statements: Statement[], emitAsReturn: boolean) {
if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) {
if (exportEquals) {
if (emitAsReturn) {
const statement = createReturn(
exportEquals.expression,
@@ -415,7 +416,7 @@ namespace ts {
)
],
/*location*/ undefined,
/*flags*/ languageVersion >= ScriptTarget.ES6 ? NodeFlags.Const : NodeFlags.None),
/*flags*/ languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None),
/*location*/ node
)
);
@@ -461,23 +462,21 @@ namespace ts {
);
}
for (const specifier of node.exportClause.elements) {
if (resolver.isValueAliasDeclaration(specifier)) {
const exportedValue = createPropertyAccess(
generatedName,
specifier.propertyName || specifier.name
);
statements.push(
createStatement(
createExportAssignment(specifier.name, exportedValue),
/*location*/ specifier
)
);
}
const exportedValue = createPropertyAccess(
generatedName,
specifier.propertyName || specifier.name
);
statements.push(
createStatement(
createExportAssignment(specifier.name, exportedValue),
/*location*/ specifier
)
);
}
return singleOrMany(statements);
}
else if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) {
else {
// export * from "mod";
return createStatement(
createCall(
@@ -495,15 +494,14 @@ namespace ts {
}
function visitExportAssignment(node: ExportAssignment): VisitResult<Statement> {
if (!node.isExportEquals) {
if (nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) {
const statements: Statement[] = [];
addExportDefault(statements, node.expression, /*location*/ node);
return statements;
}
if (node.isExportEquals) {
// Elide as `export=` is handled in addExportEqualsIfNeeded
return undefined;
}
return undefined;
const statements: Statement[] = [];
addExportDefault(statements, node.expression, /*location*/ node);
return statements;
}
function addExportDefault(statements: Statement[], expression: Expression, location: TextRange): void {
@@ -568,7 +566,7 @@ namespace ts {
}
function collectExportMembers(names: Identifier[], node: Node): Identifier[] {
if (isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && isDeclaration(node)) {
if (isAliasSymbolDeclaration(node) && isDeclaration(node)) {
const name = node.name;
if (isIdentifier(name)) {
names.push(name);
@@ -701,11 +699,13 @@ namespace ts {
const statements: Statement[] = [];
const name = node.name || getGeneratedNameForNode(node);
if (hasModifier(node, ModifierFlags.Export)) {
// Keep async modifier for ES2017 transformer
const isAsync = hasModifier(node, ModifierFlags.Async);
statements.push(
setOriginalNode(
createFunctionDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
isAsync ? [<Modifier>createNode(SyntaxKind.AsyncKeyword)] : undefined,
node.asteriskToken,
name,
/*typeParameters*/ undefined,
+20 -20
View File
@@ -91,7 +91,7 @@ namespace ts {
Debug.assert(!exportFunctionForFile);
// Collect information about the external module and dependency groups.
({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node, resolver));
({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node));
// Make sure that the name of the 'exports' function does not conflict with
// existing identifiers.
@@ -110,6 +110,7 @@ namespace ts {
const moduleName = tryGetModuleNameFromFile(node, host, compilerOptions);
const dependencies = createArrayLiteral(map(dependencyGroups, getNameOfDependencyGroup));
const body = createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -244,6 +245,7 @@ namespace ts {
),
createPropertyAssignment("execute",
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -430,6 +432,7 @@ namespace ts {
setters.push(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -573,28 +576,23 @@ namespace ts {
}
function visitExportSpecifier(specifier: ExportSpecifier): Statement {
if (resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name)
|| resolver.isValueAliasDeclaration(specifier)) {
recordExportName(specifier.name);
return createExportStatement(
specifier.name,
specifier.propertyName || specifier.name
);
}
return undefined;
recordExportName(specifier.name);
return createExportStatement(
specifier.name,
specifier.propertyName || specifier.name
);
}
function visitExportAssignment(node: ExportAssignment): Statement {
if (!node.isExportEquals) {
if (nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) {
return createExportStatement(
createLiteral("default"),
node.expression
);
}
if (node.isExportEquals) {
// Elide `export=` as it is illegal in a SystemJS module.
return undefined;
}
return undefined;
return createExportStatement(
createLiteral("default"),
node.expression
);
}
/**
@@ -662,9 +660,11 @@ namespace ts {
if (hasModifier(node, ModifierFlags.Export)) {
// If the function is exported, ensure it has a name and rewrite the function without any export flags.
const name = node.name || getGeneratedNameForNode(node);
// Keep async modifier for ES2017 transformer
const isAsync = hasModifier(node, ModifierFlags.Async);
const newNode = createFunctionDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
isAsync ? [<Modifier>createNode(SyntaxKind.AsyncKeyword)] : undefined,
node.asteriskToken,
name,
/*typeParameters*/ undefined,
@@ -1402,4 +1402,4 @@ namespace ts {
return updated;
}
}
}
}
+226 -235
View File
@@ -4,8 +4,6 @@
/*@internal*/
namespace ts {
type SuperContainer = ClassDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration;
/**
* Indicates whether to emit type metadata in the new format.
*/
@@ -16,8 +14,6 @@ namespace ts {
ClassAliases = 1 << 0,
/** Enables substitutions for namespace exports. */
NamespaceExports = 1 << 1,
/** Enables substitutions for async methods with `super` calls. */
AsyncMethodsWithSuper = 1 << 2,
/* Enables substitutions for unqualified enum members */
NonQualifiedEnumMembers = 1 << 3
}
@@ -72,12 +68,6 @@ namespace ts {
*/
let applicableSubstitutions: TypeScriptSubstitutionFlags;
/**
* This keeps track of containers where `super` is valid, for use with
* just-in-time substitution for `super` expressions inside of async methods.
*/
let currentSuperContainer: SuperContainer;
return transformSourceFile;
/**
@@ -147,6 +137,35 @@ namespace ts {
return node;
}
/**
* Specialized visitor that visits the immediate children of a SourceFile.
*
* @param node The node to visit.
*/
function sourceElementVisitor(node: Node): VisitResult<Node> {
return saveStateAndInvoke(node, sourceElementVisitorWorker);
}
/**
* Specialized visitor that visits the immediate children of a SourceFile.
*
* @param node The node to visit.
*/
function sourceElementVisitorWorker(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(<ImportDeclaration>node);
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(<ExportAssignment>node);
case SyntaxKind.ExportDeclaration:
return visitExportDeclaration(<ExportDeclaration>node);
default:
return visitorWorker(node);
}
}
/**
* Specialized visitor that visits the immediate children of a namespace.
*
@@ -244,7 +263,6 @@ namespace ts {
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.AbstractKeyword:
case SyntaxKind.AsyncKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.DeclareKeyword:
case SyntaxKind.ReadonlyKeyword:
@@ -286,8 +304,7 @@ namespace ts {
// TypeScript property declarations are elided.
case SyntaxKind.Constructor:
// TypeScript constructors are transformed in `visitClassDeclaration`.
return undefined;
return visitConstructor(<ConstructorDeclaration>node);
case SyntaxKind.InterfaceDeclaration:
// TypeScript interfaces are elided, but some comments may be preserved.
@@ -304,7 +321,6 @@ namespace ts {
// - property declarations
// - index signatures
// - method overload signatures
// - async methods
return visitClassDeclaration(<ClassDeclaration>node);
case SyntaxKind.ClassExpression:
@@ -317,7 +333,6 @@ namespace ts {
// - property declarations
// - index signatures
// - method overload signatures
// - async methods
return visitClassExpression(<ClassExpression>node);
case SyntaxKind.HeritageClause:
@@ -332,7 +347,7 @@ namespace ts {
return visitExpressionWithTypeArguments(<ExpressionWithTypeArguments>node);
case SyntaxKind.MethodDeclaration:
// TypeScript method declarations may be 'async', and may have decorators, modifiers
// TypeScript method declarations may have decorators, modifiers
// or type annotations.
return visitMethodDeclaration(<MethodDeclaration>node);
@@ -341,19 +356,19 @@ namespace ts {
return visitGetAccessor(<GetAccessorDeclaration>node);
case SyntaxKind.SetAccessor:
// Set Accessors can have TypeScript modifiers, decorators, and type annotations.
// Set Accessors can have TypeScript modifiers and type annotations.
return visitSetAccessor(<SetAccessorDeclaration>node);
case SyntaxKind.FunctionDeclaration:
// TypeScript function declarations may be 'async'
// Typescript function declarations can have modifiers, decorators, and type annotations.
return visitFunctionDeclaration(<FunctionDeclaration>node);
case SyntaxKind.FunctionExpression:
// TypeScript function expressions may be 'async'
// TypeScript function expressions can have modifiers and type annotations.
return visitFunctionExpression(<FunctionExpression>node);
case SyntaxKind.ArrowFunction:
// TypeScript arrow functions may be 'async'
// TypeScript arrow functions can have modifiers and type annotations.
return visitArrowFunction(<ArrowFunction>node);
case SyntaxKind.Parameter:
@@ -377,6 +392,12 @@ namespace ts {
// TypeScript type assertions are removed, but their subtrees are preserved.
return visitAssertionExpression(<AssertionExpression>node);
case SyntaxKind.CallExpression:
return visitCallExpression(<CallExpression>node);
case SyntaxKind.NewExpression:
return visitNewExpression(<NewExpression>node);
case SyntaxKind.NonNullExpression:
// TypeScript non-null expressions are removed, but their subtrees are preserved.
return visitNonNullExpression(<NonNullExpression>node);
@@ -385,14 +406,13 @@ namespace ts {
// TypeScript enum declarations do not exist in ES6 and must be rewritten.
return visitEnumDeclaration(<EnumDeclaration>node);
case SyntaxKind.AwaitExpression:
// TypeScript 'await' expressions must be transformed.
return visitAwaitExpression(<AwaitExpression>node);
case SyntaxKind.VariableStatement:
// TypeScript namespace exports for variable statements must be transformed.
return visitVariableStatement(<VariableStatement>node);
case SyntaxKind.VariableDeclaration:
return visitVariableDeclaration(<VariableDeclaration>node);
case SyntaxKind.ModuleDeclaration:
// TypeScript namespace declarations must be transformed.
return visitModuleDeclaration(<ModuleDeclaration>node);
@@ -436,6 +456,11 @@ namespace ts {
function visitSourceFile(node: SourceFile) {
currentSourceFile = node;
// ensure "use strict" is emitted in all scenarios in alwaysStrict mode
if (compilerOptions.alwaysStrict) {
node = ensureUseStrict(node);
}
// If the source file requires any helpers and is an external module, and
// the importHelpers compiler option is enabled, emit a synthesized import
// statement for the helpers library.
@@ -457,7 +482,7 @@ namespace ts {
statements.push(externalHelpersModuleImport);
currentSourceFileExternalHelpersModuleName = externalHelpersModuleName;
addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset));
addRange(statements, visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset));
addRange(statements, endLexicalEnvironment());
currentSourceFileExternalHelpersModuleName = undefined;
@@ -465,7 +490,7 @@ namespace ts {
node.externalHelpersModuleName = externalHelpersModuleName;
}
else {
node = visitEachChild(node, visitor, context);
node = visitEachChild(node, sourceElementVisitor, context);
}
setEmitFlags(node, EmitFlags.EmitEmitHelpers | getEmitFlags(node));
@@ -1794,7 +1819,7 @@ namespace ts {
return createIdentifier("Number");
case SyntaxKind.SymbolKeyword:
return languageVersion < ScriptTarget.ES6
return languageVersion < ScriptTarget.ES2015
? getGlobalSymbolNameWithFallback()
: createIdentifier("Symbol");
@@ -1891,7 +1916,7 @@ namespace ts {
return createIdentifier("Array");
case TypeReferenceSerializationKind.ESSymbolType:
return languageVersion < ScriptTarget.ES6
return languageVersion < ScriptTarget.ES2015
? getGlobalSymbolNameWithFallback()
: createIdentifier("Symbol");
@@ -2083,12 +2108,20 @@ namespace ts {
return !nodeIsMissing(node.body);
}
function visitConstructor(node: ConstructorDeclaration) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return undefined;
}
return visitEachChild(node, 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, async, public, private, protected, or readonly
* - The node is marked as abstract, public, private, protected, or readonly
* - The node has both a decorator and a computed property name
*
* @param node The method node.
@@ -2199,8 +2232,8 @@ namespace ts {
*
* This function will be called when one of the following conditions are met:
* - The node is an overload
* - The node is marked async
* - The node is exported from a TypeScript namespace
* - The node has decorators
*
* @param node The function node.
*/
@@ -2235,7 +2268,7 @@ namespace ts {
* Visits a function expression node.
*
* This function will be called when one of the following conditions are met:
* - The node is marked async
* - The node has type annotations
*
* @param node The function expression node.
*/
@@ -2245,6 +2278,7 @@ namespace ts {
}
const func = createFunctionExpression(
visitNodes(node.modifiers, visitor, isModifier),
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
@@ -2262,11 +2296,11 @@ namespace ts {
/**
* @remarks
* This function will be called when one of the following conditions are met:
* - The node is marked async
* - The node has type annotations
*/
function visitArrowFunction(node: ArrowFunction) {
const func = createArrowFunction(
/*modifiers*/ undefined,
visitNodes(node.modifiers, visitor, isModifier),
/*typeParameters*/ undefined,
visitNodes(node.parameters, visitor, isParameter),
/*type*/ undefined,
@@ -2281,30 +2315,25 @@ namespace ts {
}
function transformFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody {
if (isAsyncFunctionLike(node)) {
return <FunctionBody>transformAsyncFunctionBody(node);
}
return transformFunctionBodyWorker(node.body);
}
function transformFunctionBodyWorker(body: Block, start = 0) {
const savedCurrentScope = currentScope;
const savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
currentScope = body;
currentScopeFirstDeclarationsOfName = new StringMap<Node>();
startLexicalEnvironment();
const statements = visitNodes(body.statements, visitor, isStatement, start);
const visited = updateBlock(body, statements);
const declarations = endLexicalEnvironment();
currentScope = savedCurrentScope;
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
return mergeFunctionBodyLexicalEnvironment(visited, declarations);
}
function transformConciseBody(node: ArrowFunction): ConciseBody {
if (isAsyncFunctionLike(node)) {
return transformAsyncFunctionBody(node);
}
return transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ false);
}
@@ -2328,72 +2357,6 @@ namespace ts {
}
}
function getPromiseConstructor(type: TypeNode) {
const typeName = getEntityNameFromTypeNode(type);
if (typeName && isEntityName(typeName)) {
const serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
if (serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
|| serializationKind === TypeReferenceSerializationKind.Unknown) {
return typeName;
}
}
return undefined;
}
function transformAsyncFunctionBody(node: FunctionLikeDeclaration): ConciseBody | FunctionBody {
const promiseConstructor = languageVersion < ScriptTarget.ES6 ? getPromiseConstructor(node.type) : undefined;
const isArrowFunction = node.kind === SyntaxKind.ArrowFunction;
const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0;
// An async function is emit as an outer function that calls an inner
// generator function. To preserve lexical bindings, we pass the current
// `this` and `arguments` objects to `__awaiter`. The generator function
// passed to `__awaiter` is executed inside of the callback to the
// promise constructor.
if (!isArrowFunction) {
const statements: Statement[] = [];
const statementOffset = addPrologueDirectives(statements, (<Block>node.body).statements, /*ensureUseStrict*/ false, visitor);
statements.push(
createReturn(
createAwaiterHelper(
currentSourceFileExternalHelpersModuleName,
hasLexicalArguments,
promiseConstructor,
transformFunctionBodyWorker(<Block>node.body, statementOffset)
)
)
);
const block = createBlock(statements, /*location*/ node.body, /*multiLine*/ true);
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
if (languageVersion >= ScriptTarget.ES6) {
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) {
enableSubstitutionForAsyncMethodsWithSuper();
setEmitFlags(block, EmitFlags.EmitAdvancedSuperHelper);
}
else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuper) {
enableSubstitutionForAsyncMethodsWithSuper();
setEmitFlags(block, EmitFlags.EmitSuperHelper);
}
}
return block;
}
else {
return createAwaiterHelper(
currentSourceFileExternalHelpersModuleName,
hasLexicalArguments,
promiseConstructor,
<Block>transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ true)
);
}
}
/**
* Visits a parameter declaration node.
*
@@ -2476,22 +2439,12 @@ namespace ts {
}
}
/**
* Visits an await expression.
*
* This function will be called any time a TypeScript await expression is encountered.
*
* @param node The await expression node.
*/
function visitAwaitExpression(node: AwaitExpression): Expression {
return setOriginalNode(
createYield(
/*asteriskToken*/ undefined,
visitNode(node.expression, visitor, isExpression),
/*location*/ node
),
node
);
function visitVariableDeclaration(node: VariableDeclaration) {
return updateVariableDeclaration(
node,
visitNode(node.name, visitor, isBindingName),
/*type*/ undefined,
visitNode(node.initializer, visitor, isExpression));
}
/**
@@ -2536,6 +2489,22 @@ namespace ts {
return createPartiallyEmittedExpression(expression, node);
}
function visitCallExpression(node: CallExpression) {
return updateCall(
node,
visitNode(node.expression, visitor, isExpression),
/*typeArguments*/ undefined,
visitNodes(node.arguments, visitor, isExpression));
}
function visitNewExpression(node: NewExpression) {
return updateNew(
node,
visitNode(node.expression, visitor, isExpression),
/*typeArguments*/ undefined,
visitNodes(node.arguments, visitor, isExpression));
}
/**
* Determines whether to emit an enum declaration.
*
@@ -2617,6 +2586,7 @@ namespace ts {
const enumStatement = createStatement(
createCall(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -2730,7 +2700,7 @@ namespace ts {
function isES6ExportedDeclaration(node: Node) {
return isExternalModuleExport(node)
&& moduleKind === ModuleKind.ES6;
&& moduleKind === ModuleKind.ES2015;
}
/**
@@ -2886,6 +2856,7 @@ namespace ts {
const moduleStatement = createStatement(
createCall(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
@@ -2991,6 +2962,133 @@ namespace ts {
}
}
/**
* Visits an import declaration, eliding it if it is not referenced.
*
* @param node The import declaration node.
*/
function visitImportDeclaration(node: ImportDeclaration): VisitResult<Statement> {
if (!node.importClause) {
// Do not elide a side-effect only import declaration.
// import "foo";
return node;
}
// Elide the declaration if the import clause was elided.
const importClause = visitNode(node.importClause, visitImportClause, isImportClause, /*optional*/ true);
return importClause
? updateImportDeclaration(
node,
/*decorators*/ undefined,
/*modifiers*/ undefined,
importClause,
node.moduleSpecifier)
: undefined;
}
/**
* Visits an import clause, eliding it if it is not referenced.
*
* @param node The import clause node.
*/
function visitImportClause(node: ImportClause): VisitResult<ImportClause> {
// Elide the import clause if we elide both its name and its named bindings.
const name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
const namedBindings = visitNode(node.namedBindings, visitNamedImportBindings, isNamedImportBindings, /*optional*/ true);
return (name || namedBindings) ? updateImportClause(node, name, namedBindings) : undefined;
}
/**
* Visits named import bindings, eliding it if it is not referenced.
*
* @param node The named import bindings node.
*/
function visitNamedImportBindings(node: NamedImportBindings): VisitResult<NamedImportBindings> {
if (node.kind === SyntaxKind.NamespaceImport) {
// Elide a namespace import if it is not referenced.
return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
else {
// Elide named imports if all of its import specifiers are elided.
const elements = visitNodes(node.elements, visitImportSpecifier, isImportSpecifier);
return some(elements) ? updateNamedImports(node, elements) : undefined;
}
}
/**
* Visits an import specifier, eliding it if it is not referenced.
*
* @param node The import specifier node.
*/
function visitImportSpecifier(node: ImportSpecifier): VisitResult<ImportSpecifier> {
// Elide an import specifier if it is not referenced.
return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
/**
* Visits an export assignment, eliding it if it does not contain a clause that resolves
* to a value.
*
* @param node The export assignment node.
*/
function visitExportAssignment(node: ExportAssignment): VisitResult<Statement> {
// Elide the export assignment if it does not reference a value.
return resolver.isValueAliasDeclaration(node)
? visitEachChild(node, visitor, context)
: undefined;
}
/**
* Visits an export declaration, eliding it if it does not contain a clause that resolves
* to a value.
*
* @param node The export declaration node.
*/
function visitExportDeclaration(node: ExportDeclaration): VisitResult<Statement> {
if (!node.exportClause) {
// Elide a star export if the module it references does not export a value.
return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined;
}
if (!resolver.isValueAliasDeclaration(node)) {
// Elide the export declaration if it does not export a value.
return undefined;
}
// Elide the export declaration if all of its named exports are elided.
const exportClause = visitNode(node.exportClause, visitNamedExports, isNamedExports, /*optional*/ true);
return exportClause
? updateExportDeclaration(
node,
/*decorators*/ undefined,
/*modifiers*/ undefined,
exportClause,
node.moduleSpecifier)
: undefined;
}
/**
* Visits named exports, eliding it if it does not contain an export specifier that
* resolves to a value.
*
* @param node The named exports node.
*/
function visitNamedExports(node: NamedExports): VisitResult<NamedExports> {
// Elide the named exports if all of its export specifiers were elided.
const elements = visitNodes(node.elements, visitExportSpecifier, isExportSpecifier);
return some(elements) ? updateNamedExports(node, elements) : undefined;
}
/**
* Visits an export specifier, eliding it if it does not resolve to a value.
*
* @param node The export specifier node.
*/
function visitExportSpecifier(node: ExportSpecifier): VisitResult<ExportSpecifier> {
// Elide an export specifier if it does not reference a value.
return resolver.isValueAliasDeclaration(node) ? node : undefined;
}
/**
* Determines whether to emit an import equals declaration.
*
@@ -3012,7 +3110,10 @@ namespace ts {
*/
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult<Statement> {
if (isExternalModuleImportEqualsDeclaration(node)) {
return visitEachChild(node, visitor, context);
// Elide external module `import=` if it is not referenced.
return resolver.isReferencedAliasDeclaration(node)
? visitEachChild(node, visitor, context)
: undefined;
}
if (!shouldEmitImportEqualsDeclaration(node)) {
@@ -3246,25 +3347,6 @@ namespace ts {
}
}
function enableSubstitutionForAsyncMethodsWithSuper() {
if ((enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper) === 0) {
enabledSubstitutions |= TypeScriptSubstitutionFlags.AsyncMethodsWithSuper;
// We need to enable substitutions for call, property access, and element access
// if we need to rewrite super calls.
context.enableSubstitution(SyntaxKind.CallExpression);
context.enableSubstitution(SyntaxKind.PropertyAccessExpression);
context.enableSubstitution(SyntaxKind.ElementAccessExpression);
// We need to be notified when entering and exiting declarations that bind super.
context.enableEmitNotification(SyntaxKind.ClassDeclaration);
context.enableEmitNotification(SyntaxKind.MethodDeclaration);
context.enableEmitNotification(SyntaxKind.GetAccessor);
context.enableEmitNotification(SyntaxKind.SetAccessor);
context.enableEmitNotification(SyntaxKind.Constructor);
}
}
function enableSubstitutionForClassAliases() {
if ((enabledSubstitutions & TypeScriptSubstitutionFlags.ClassAliases) === 0) {
enabledSubstitutions |= TypeScriptSubstitutionFlags.ClassAliases;
@@ -3292,15 +3374,6 @@ namespace ts {
}
}
function isSuperContainer(node: Node): node is SuperContainer {
const kind = node.kind;
return kind === SyntaxKind.ClassDeclaration
|| kind === SyntaxKind.Constructor
|| kind === SyntaxKind.MethodDeclaration
|| kind === SyntaxKind.GetAccessor
|| kind === SyntaxKind.SetAccessor;
}
function isTransformedModuleDeclaration(node: Node): boolean {
return getOriginalNode(node).kind === SyntaxKind.ModuleDeclaration;
}
@@ -3317,12 +3390,6 @@ namespace ts {
*/
function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void {
const savedApplicableSubstitutions = applicableSubstitutions;
const savedCurrentSuperContainer = currentSuperContainer;
// If we need to support substitutions for `super` in an async method,
// we should track it here.
if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper && isSuperContainer(node)) {
currentSuperContainer = node;
}
if (enabledSubstitutions & TypeScriptSubstitutionFlags.NamespaceExports && isTransformedModuleDeclaration(node)) {
applicableSubstitutions |= TypeScriptSubstitutionFlags.NamespaceExports;
@@ -3335,7 +3402,6 @@ namespace ts {
previousOnEmitNode(emitContext, node, emitCallback);
applicableSubstitutions = savedApplicableSubstitutions;
currentSuperContainer = savedCurrentSuperContainer;
}
/**
@@ -3382,11 +3448,6 @@ namespace ts {
return substitutePropertyAccessExpression(<PropertyAccessExpression>node);
case SyntaxKind.ElementAccessExpression:
return substituteElementAccessExpression(<ElementAccessExpression>node);
case SyntaxKind.CallExpression:
if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper) {
return substituteCallExpression(<CallExpression>node);
}
break;
}
return node;
@@ -3441,54 +3502,11 @@ namespace ts {
return undefined;
}
function substituteCallExpression(node: CallExpression): Expression {
const expression = node.expression;
if (isSuperProperty(expression)) {
const flags = getSuperContainerAsyncMethodFlags();
if (flags) {
const argumentExpression = isPropertyAccessExpression(expression)
? substitutePropertyAccessExpression(expression)
: substituteElementAccessExpression(expression);
return createCall(
createPropertyAccess(argumentExpression, "call"),
/*typeArguments*/ undefined,
[
createThis(),
...node.arguments
]
);
}
}
return node;
}
function substitutePropertyAccessExpression(node: PropertyAccessExpression) {
if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) {
const flags = getSuperContainerAsyncMethodFlags();
if (flags) {
return createSuperAccessInAsyncMethod(
createLiteral(node.name.text),
flags,
node
);
}
}
return substituteConstantValue(node);
}
function substituteElementAccessExpression(node: ElementAccessExpression) {
if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) {
const flags = getSuperContainerAsyncMethodFlags();
if (flags) {
return createSuperAccessInAsyncMethod(
node.argumentExpression,
flags,
node
);
}
}
return substituteConstantValue(node);
}
@@ -3521,32 +3539,5 @@ namespace ts {
? resolver.getConstantValue(<PropertyAccessExpression | ElementAccessExpression>node)
: undefined;
}
function createSuperAccessInAsyncMethod(argumentExpression: Expression, flags: NodeCheckFlags, location: TextRange): LeftHandSideExpression {
if (flags & NodeCheckFlags.AsyncMethodWithSuperBinding) {
return createPropertyAccess(
createCall(
createIdentifier("_super"),
/*typeArguments*/ undefined,
[argumentExpression]
),
"value",
location
);
}
else {
return createCall(
createIdentifier("_super"),
/*typeArguments*/ undefined,
[argumentExpression],
location
);
}
}
function getSuperContainerAsyncMethodFlags() {
return currentSuperContainer !== undefined
&& resolver.getNodeCheckFlags(currentSuperContainer) & (NodeCheckFlags.AsyncMethodWithSuper | NodeCheckFlags.AsyncMethodWithSuperBinding);
}
}
}
+4 -3
View File
@@ -25,13 +25,14 @@
"visitor.ts",
"transformers/ts.ts",
"transformers/jsx.ts",
"transformers/es7.ts",
"transformers/es6.ts",
"transformers/es2017.ts",
"transformers/es2016.ts",
"transformers/es2015.ts",
"transformers/generators.ts",
"transformers/destructuring.ts",
"transformers/module/module.ts",
"transformers/module/system.ts",
"transformers/module/es6.ts",
"transformers/module/es2015.ts",
"transformer.ts",
"comments.ts",
"sourcemap.ts",
+52 -40
View File
@@ -491,6 +491,8 @@ namespace ts {
// Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
ParameterPropertyModifier = AccessibilityModifier | Readonly,
NonPublicAccessibilityModifier = Private | Protected,
TypeScriptModifier = Ambient | Public | Private | Protected | Readonly | Abstract | Const
}
export const enum JsxFlags {
@@ -1942,8 +1944,9 @@ namespace ts {
TrueCondition = 1 << 5, // Condition known to be true
FalseCondition = 1 << 6, // Condition known to be false
SwitchClause = 1 << 7, // Switch statement clause
Referenced = 1 << 8, // Referenced as antecedent once
Shared = 1 << 9, // Referenced as antecedent more than once
ArrayMutation = 1 << 8, // Potential array mutation
Referenced = 1 << 9, // Referenced as antecedent once
Shared = 1 << 10, // Referenced as antecedent more than once
Label = BranchLabel | LoopLabel,
Condition = TrueCondition | FalseCondition
}
@@ -1957,7 +1960,7 @@ namespace ts {
// function, the container property references the function (which in turn has a flowNode
// property for the containing control flow).
export interface FlowStart extends FlowNode {
container?: FunctionExpression | ArrowFunction;
container?: FunctionExpression | ArrowFunction | MethodDeclaration;
}
// FlowLabel represents a junction with multiple possible preceding control flows.
@@ -1986,6 +1989,13 @@ namespace ts {
antecedent: FlowNode;
}
// FlowArrayMutation represents a node potentially mutates an array, i.e. an
// operation of the form 'x.push(value)', 'x.unshift(value)' or 'x[n] = value'.
export interface FlowArrayMutation extends FlowNode {
node: CallExpression | BinaryExpression;
antecedent: FlowNode;
}
export type FlowType = Type | IncompleteType;
// Incomplete types occur during control flow analysis of loops. An IncompleteType
@@ -2679,7 +2689,7 @@ namespace ts {
// 'Narrowable' types are types where narrowing actually narrows.
// This *should* be every type other than null, undefined, void, and never
Narrowable = Any | StructuredType | TypeParameter | StringLike | NumberLike | BooleanLike | ESSymbol,
NotUnionOrUnit = Any | String | Number | ESSymbol | ObjectType,
NotUnionOrUnit = Any | ESSymbol | ObjectType,
/* @internal */
RequiresWidening = ContainsWideningType | ContainsObjectLiteral,
/* @internal */
@@ -2783,6 +2793,8 @@ namespace ts {
export interface AnonymousType extends ObjectType {
target?: AnonymousType; // Instantiation target
mapper?: TypeMapper; // Instantiation mapper
elementType?: Type; // Element expressions of evolving array type
finalArrayType?: Type; // Final array type of evolving array type
}
/* @internal */
@@ -2952,11 +2964,7 @@ namespace ts {
NodeJs = 2
}
export type RootPaths = string[];
export type PathSubstitutions = MapLike<string[]>;
export type TsConfigOnlyOptions = RootPaths | PathSubstitutions;
export type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions;
export type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike<string[]>;
export interface CompilerOptions {
allowJs?: boolean;
@@ -2964,6 +2972,7 @@ namespace ts {
allowSyntheticDefaultImports?: boolean;
allowUnreachableCode?: boolean;
allowUnusedLabels?: boolean;
alwaysStrict?: boolean;
baseUrl?: string;
charset?: string;
/* @internal */ configFilePath?: string;
@@ -3008,14 +3017,14 @@ namespace ts {
out?: string;
outDir?: string;
outFile?: string;
paths?: PathSubstitutions;
paths?: MapLike<string[]>;
preserveConstEnums?: boolean;
project?: string;
/* @internal */ pretty?: DiagnosticStyle;
reactNamespace?: string;
removeComments?: boolean;
rootDir?: string;
rootDirs?: RootPaths;
rootDirs?: string[];
skipLibCheck?: boolean;
skipDefaultLibCheck?: boolean;
sourceMap?: boolean;
@@ -3058,8 +3067,7 @@ namespace ts {
AMD = 2,
UMD = 3,
System = 4,
ES6 = 5,
ES2015 = ES6,
ES2015 = 5,
}
export const enum JsxEmit {
@@ -3092,9 +3100,10 @@ namespace ts {
export const enum ScriptTarget {
ES3 = 0,
ES5 = 1,
ES6 = 2,
ES2015 = ES6,
Latest = ES6,
ES2015 = 2,
ES2016 = 3,
ES2017 = 4,
Latest = ES2017,
}
export const enum LanguageVariant {
@@ -3379,29 +3388,31 @@ namespace ts {
ContainsTypeScript = 1 << 1,
Jsx = 1 << 2,
ContainsJsx = 1 << 3,
ES7 = 1 << 4,
ContainsES7 = 1 << 5,
ES6 = 1 << 6,
ContainsES6 = 1 << 7,
DestructuringAssignment = 1 << 8,
Generator = 1 << 9,
ContainsGenerator = 1 << 10,
ES2017 = 1 << 4,
ContainsES2017 = 1 << 5,
ES2016 = 1 << 6,
ContainsES2016 = 1 << 7,
ES2015 = 1 << 8,
ContainsES2015 = 1 << 9,
DestructuringAssignment = 1 << 10,
Generator = 1 << 11,
ContainsGenerator = 1 << 12,
// Markers
// - Flags used to indicate that a subtree contains a specific transformation.
ContainsDecorators = 1 << 11,
ContainsPropertyInitializer = 1 << 12,
ContainsLexicalThis = 1 << 13,
ContainsCapturedLexicalThis = 1 << 14,
ContainsLexicalThisInComputedPropertyName = 1 << 15,
ContainsDefaultValueAssignments = 1 << 16,
ContainsParameterPropertyAssignments = 1 << 17,
ContainsSpreadElementExpression = 1 << 18,
ContainsComputedPropertyName = 1 << 19,
ContainsBlockScopedBinding = 1 << 20,
ContainsBindingPattern = 1 << 21,
ContainsYield = 1 << 22,
ContainsHoistedDeclarationOrCompletion = 1 << 23,
ContainsDecorators = 1 << 13,
ContainsPropertyInitializer = 1 << 14,
ContainsLexicalThis = 1 << 15,
ContainsCapturedLexicalThis = 1 << 16,
ContainsLexicalThisInComputedPropertyName = 1 << 17,
ContainsDefaultValueAssignments = 1 << 18,
ContainsParameterPropertyAssignments = 1 << 19,
ContainsSpreadElementExpression = 1 << 20,
ContainsComputedPropertyName = 1 << 21,
ContainsBlockScopedBinding = 1 << 22,
ContainsBindingPattern = 1 << 23,
ContainsYield = 1 << 24,
ContainsHoistedDeclarationOrCompletion = 1 << 25,
HasComputedFlags = 1 << 29, // Transform flags have been computed.
@@ -3409,14 +3420,15 @@ namespace ts {
// - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
AssertTypeScript = TypeScript | ContainsTypeScript,
AssertJsx = Jsx | ContainsJsx,
AssertES7 = ES7 | ContainsES7,
AssertES6 = ES6 | ContainsES6,
AssertES2017 = ES2017 | ContainsES2017,
AssertES2016 = ES2016 | ContainsES2016,
AssertES2015 = ES2015 | ContainsES2015,
AssertGenerator = Generator | ContainsGenerator,
// Scope Exclusions
// - Bitmasks that exclude flags from propagating out of a specific context
// into the subtree flags of their container.
NodeExcludes = TypeScript | Jsx | ES7 | ES6 | DestructuringAssignment | Generator | HasComputedFlags,
NodeExcludes = TypeScript | Jsx | ES2017 | ES2016 | ES2015 | DestructuringAssignment | Generator | HasComputedFlags,
ArrowFunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
FunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
@@ -3432,7 +3444,7 @@ namespace ts {
// Masks
// - Additional bitmasks
TypeScriptClassSyntaxMask = ContainsParameterPropertyAssignments | ContainsPropertyInitializer | ContainsDecorators,
ES6FunctionSyntaxMask = ContainsCapturedLexicalThis | ContainsDefaultValueAssignments,
ES2015FunctionSyntaxMask = ContainsCapturedLexicalThis | ContainsDefaultValueAssignments,
}
/* @internal */
+35 -20
View File
@@ -337,7 +337,7 @@ namespace ts {
export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile, languageVersion: ScriptTarget) {
// Any template literal or string literal with an extended escape
// (e.g. "\u{0067}") will need to be downleveled as a escaped string literal.
if (languageVersion < ScriptTarget.ES6 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) {
if (languageVersion < ScriptTarget.ES2015 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) {
return getQuotedEscapedLiteralText('"', node.text, '"');
}
@@ -345,7 +345,7 @@ namespace ts {
// the node's parent reference, then simply get the text as it was originally written.
if (!nodeIsSynthesized(node) && node.parent) {
const text = getSourceTextOfNodeFromSourceFile(sourceFile, node);
if (languageVersion < ScriptTarget.ES6 && isBinaryOrOctalIntegerLiteral(node, text)) {
if (languageVersion < ScriptTarget.ES2015 && isBinaryOrOctalIntegerLiteral(node, text)) {
return node.text;
}
return text;
@@ -895,6 +895,12 @@ namespace ts {
return node && node.kind === SyntaxKind.MethodDeclaration && node.parent.kind === SyntaxKind.ObjectLiteralExpression;
}
export function isObjectLiteralOrClassExpressionMethod(node: Node): node is MethodDeclaration {
return node.kind === SyntaxKind.MethodDeclaration &&
(node.parent.kind === SyntaxKind.ObjectLiteralExpression ||
node.parent.kind === SyntaxKind.ClassExpression);
}
export function isIdentifierTypePredicate(predicate: TypePredicate): predicate is IdentifierTypePredicate {
return predicate && predicate.kind === TypePredicateKind.Identifier;
}
@@ -1895,6 +1901,10 @@ namespace ts {
return node.kind === SyntaxKind.Identifier && (<Identifier>node).text === "Symbol";
}
export function isPushOrUnshiftIdentifier(node: Identifier) {
return node.text === "push" || node.text === "unshift";
}
export function isModifierKind(token: SyntaxKind): boolean {
switch (token) {
case SyntaxKind.AbstractKeyword:
@@ -3496,7 +3506,7 @@ namespace ts {
return positionIsSynthesized(range.pos) ? -1 : skipTrivia(sourceFile.text, range.pos);
}
export function collectExternalModuleInfo(sourceFile: SourceFile, resolver: EmitResolver) {
export function collectExternalModuleInfo(sourceFile: SourceFile) {
const externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[] = [];
const exportSpecifiers = new StringMap<ExportSpecifier[]>();
let exportEquals: ExportAssignment = undefined;
@@ -3504,19 +3514,16 @@ namespace ts {
for (const node of sourceFile.statements) {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
if (!(<ImportDeclaration>node).importClause ||
resolver.isReferencedAliasDeclaration((<ImportDeclaration>node).importClause, /*checkChildren*/ true)) {
// import "mod"
// import x from "mod" where x is referenced
// import * as x from "mod" where x is referenced
// import { x, y } from "mod" where at least one import is referenced
externalImports.push(<ImportDeclaration>node);
}
// import "mod"
// import x from "mod"
// import * as x from "mod"
// import { x, y } from "mod"
externalImports.push(<ImportDeclaration>node);
break;
case SyntaxKind.ImportEqualsDeclaration:
if ((<ImportEqualsDeclaration>node).moduleReference.kind === SyntaxKind.ExternalModuleReference && resolver.isReferencedAliasDeclaration(node)) {
// import x = require("mod") where x is referenced
if ((<ImportEqualsDeclaration>node).moduleReference.kind === SyntaxKind.ExternalModuleReference) {
// import x = require("mod")
externalImports.push(<ImportEqualsDeclaration>node);
}
break;
@@ -3525,13 +3532,11 @@ namespace ts {
if ((<ExportDeclaration>node).moduleSpecifier) {
if (!(<ExportDeclaration>node).exportClause) {
// export * from "mod"
if (resolver.moduleExportsSomeValue((<ExportDeclaration>node).moduleSpecifier)) {
externalImports.push(<ExportDeclaration>node);
hasExportStarsToExportValues = true;
}
externalImports.push(<ExportDeclaration>node);
hasExportStarsToExportValues = true;
}
else if (resolver.isValueAliasDeclaration(node)) {
// export { x, y } from "mod" where at least one export is a value symbol
else {
// export { x, y } from "mod"
externalImports.push(<ExportDeclaration>node);
}
}
@@ -4161,7 +4166,17 @@ namespace ts {
namespace ts {
export function getDefaultLibFileName(options: CompilerOptions): string {
return options.target === ScriptTarget.ES6 ? "lib.es6.d.ts" : "lib.d.ts";
switch (options.target) {
case ScriptTarget.ES2017:
return "lib.es2017.d.ts";
case ScriptTarget.ES2016:
return "lib.es2016.d.ts";
case ScriptTarget.ES2015:
return "lib.es2015.d.ts";
default:
return "lib.d.ts";
}
}
export function textSpanEnd(span: TextSpan) {
+2 -1
View File
@@ -807,6 +807,7 @@ namespace ts {
case SyntaxKind.FunctionExpression:
return updateFunctionExpression(<FunctionExpression>node,
visitNodes((<FunctionExpression>node).modifiers, visitor, isModifier),
visitNode((<FunctionExpression>node).name, visitor, isPropertyName),
visitNodes((<FunctionExpression>node).typeParameters, visitor, isTypeParameter),
(context.startLexicalEnvironment(), visitNodes((<FunctionExpression>node).parameters, visitor, isParameter)),
@@ -1357,4 +1358,4 @@ namespace ts {
}
}
}
}
}
+12 -2
View File
@@ -941,7 +941,17 @@ namespace Harness {
}
export function getDefaultLibFileName(options: ts.CompilerOptions): string {
return options.target === ts.ScriptTarget.ES6 ? es2015DefaultLibFileName : defaultLibFileName;
switch (options.target) {
case ts.ScriptTarget.ES2017:
return "lib.es2017.d.ts";
case ts.ScriptTarget.ES2016:
return "lib.es2016.d.ts";
case ts.ScriptTarget.ES2015:
return es2015DefaultLibFileName;
default:
return defaultLibFileName;
}
}
// Cache these between executions so we don't have to re-parse them for every test
@@ -1634,7 +1644,7 @@ namespace Harness {
export function collateOutputs(outputFiles: Harness.Compiler.GeneratedFile[]): string {
// Collect, test, and sort the fileNames
outputFiles.sort((a, b) => cleanName(a.fileName).localeCompare(cleanName(b.fileName)));
outputFiles.sort((a, b) => ts.compareStrings(cleanName(a.fileName), cleanName(b.fileName)));
// Emit them
let result = "";
+4 -3
View File
@@ -26,13 +26,14 @@
"../compiler/visitor.ts",
"../compiler/transformers/ts.ts",
"../compiler/transformers/jsx.ts",
"../compiler/transformers/es7.ts",
"../compiler/transformers/es6.ts",
"../compiler/transformers/es2017.ts",
"../compiler/transformers/es2016.ts",
"../compiler/transformers/es2015.ts",
"../compiler/transformers/generators.ts",
"../compiler/transformers/destructuring.ts",
"../compiler/transformers/module/module.ts",
"../compiler/transformers/module/system.ts",
"../compiler/transformers/module/es6.ts",
"../compiler/transformers/module/es2015.ts",
"../compiler/transformer.ts",
"../compiler/comments.ts",
"../compiler/sourcemap.ts",
+1 -1
View File
@@ -165,7 +165,7 @@ namespace ts {
start: undefined,
length: undefined,
}, {
messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015'",
messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017'",
category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
+21 -19
View File
@@ -3,6 +3,8 @@
/// <reference path="../../server/typingsInstaller/typingsInstaller.ts" />
namespace ts.projectSystem {
import CommandNames = server.CommandNames;
function createTestTypingsInstaller(host: server.ServerHost) {
return new TestTypingsInstaller("/a/data/", /*throttleLimit*/5, host);
}
@@ -75,7 +77,7 @@ namespace ts.projectSystem {
};
// Change the content of file1 to `export var T: number;export function Foo() { };`
changeModuleFile1ShapeRequest1 = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
changeModuleFile1ShapeRequest1 = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: moduleFile1.path,
line: 1,
offset: 1,
@@ -85,7 +87,7 @@ namespace ts.projectSystem {
});
// Change the content of file1 to `export var T: number;export function Foo() { };`
changeModuleFile1InternalRequest1 = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
changeModuleFile1InternalRequest1 = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: moduleFile1.path,
line: 1,
offset: 1,
@@ -95,7 +97,7 @@ namespace ts.projectSystem {
});
// Change the content of file1 to `export var T: number;export function Foo() { };`
changeModuleFile1ShapeRequest2 = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
changeModuleFile1ShapeRequest2 = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: moduleFile1.path,
line: 1,
offset: 1,
@@ -104,7 +106,7 @@ namespace ts.projectSystem {
insertString: `export var T2: number;`
});
moduleFile1FileListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(server.CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path, projectFileName: configFile.path });
moduleFile1FileListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path, projectFileName: configFile.path });
});
it("should contains only itself if a module file's shape didn't change, and all files referencing it if its shape changed", () => {
@@ -120,7 +122,7 @@ namespace ts.projectSystem {
sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer2] }]);
// Change the content of file1 to `export var T: number;export function Foo() { console.log('hi'); };`
const changeFile1InternalRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const changeFile1InternalRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: moduleFile1.path,
line: 1,
offset: 46,
@@ -143,7 +145,7 @@ namespace ts.projectSystem {
sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer2] }]);
// Change file2 content to `let y = Foo();`
const removeFile1Consumer1ImportRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const removeFile1Consumer1ImportRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: file1Consumer1.path,
line: 1,
offset: 1,
@@ -156,7 +158,7 @@ namespace ts.projectSystem {
sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer2] }]);
// Add the import statements back to file2
const addFile2ImportRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const addFile2ImportRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: file1Consumer1.path,
line: 1,
offset: 1,
@@ -167,7 +169,7 @@ namespace ts.projectSystem {
session.executeCommand(addFile2ImportRequest);
// Change the content of file1 to `export var T2: string;export var T: number;export function Foo() { };`
const changeModuleFile1ShapeRequest2 = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const changeModuleFile1ShapeRequest2 = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: moduleFile1.path,
line: 1,
offset: 1,
@@ -272,7 +274,7 @@ namespace ts.projectSystem {
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
openFilesForSession([globalFile3], session);
const changeGlobalFile3ShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const changeGlobalFile3ShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: globalFile3.path,
line: 1,
offset: 1,
@@ -283,7 +285,7 @@ namespace ts.projectSystem {
// check after file1 shape changes
session.executeCommand(changeGlobalFile3ShapeRequest);
const globalFile3FileListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(server.CommandNames.CompileOnSaveAffectedFileList, { file: globalFile3.path });
const globalFile3FileListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(CommandNames.CompileOnSaveAffectedFileList, { file: globalFile3.path });
sendAffectedFileRequestAndCheckResult(session, globalFile3FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer2, globalFile3, moduleFile2] }]);
});
@@ -316,7 +318,7 @@ namespace ts.projectSystem {
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
openFilesForSession([moduleFile1], session);
const file1ChangeShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const file1ChangeShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: moduleFile1.path,
line: 1,
offset: 27,
@@ -345,7 +347,7 @@ namespace ts.projectSystem {
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
openFilesForSession([moduleFile1], session);
const file1ChangeShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const file1ChangeShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: moduleFile1.path,
line: 1,
offset: 27,
@@ -369,7 +371,7 @@ namespace ts.projectSystem {
openFilesForSession([moduleFile1, file1Consumer1], session);
sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer1Consumer1] }]);
const changeFile1Consumer1ShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(server.CommandNames.Change, {
const changeFile1Consumer1ShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
file: file1Consumer1.path,
line: 2,
offset: 1,
@@ -400,7 +402,7 @@ namespace ts.projectSystem {
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
openFilesForSession([file1, file2], session);
const file1AffectedListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(server.CommandNames.CompileOnSaveAffectedFileList, { file: file1.path });
const file1AffectedListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(CommandNames.CompileOnSaveAffectedFileList, { file: file1.path });
sendAffectedFileRequestAndCheckResult(session, file1AffectedListRequest, [{ projectFileName: configFile.path, files: [file1, file2] }]);
});
@@ -415,7 +417,7 @@ namespace ts.projectSystem {
const session = createSession(host);
openFilesForSession([file1, file2, file3], session);
const file1AffectedListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(server.CommandNames.CompileOnSaveAffectedFileList, { file: file1.path });
const file1AffectedListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(CommandNames.CompileOnSaveAffectedFileList, { file: file1.path });
sendAffectedFileRequestAndCheckResult(session, file1AffectedListRequest, [
{ projectFileName: configFile1.path, files: [file1, file2] },
@@ -437,11 +439,11 @@ namespace ts.projectSystem {
host.reloadFS([referenceFile1, configFile]);
host.triggerFileWatcherCallback(moduleFile1.path, /*removed*/ true);
const request = makeSessionRequest<server.protocol.FileRequestArgs>(server.CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path });
const request = makeSessionRequest<server.protocol.FileRequestArgs>(CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path });
sendAffectedFileRequestAndCheckResult(session, request, [
{ projectFileName: configFile.path, files: [referenceFile1] }
]);
const requestForMissingFile = makeSessionRequest<server.protocol.FileRequestArgs>(server.CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path });
const requestForMissingFile = makeSessionRequest<server.protocol.FileRequestArgs>(CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path });
sendAffectedFileRequestAndCheckResult(session, requestForMissingFile, []);
});
@@ -456,7 +458,7 @@ namespace ts.projectSystem {
const session = createSession(host);
openFilesForSession([referenceFile1], session);
const request = makeSessionRequest<server.protocol.FileRequestArgs>(server.CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path });
const request = makeSessionRequest<server.protocol.FileRequestArgs>(CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path });
sendAffectedFileRequestAndCheckResult(session, request, [
{ projectFileName: configFile.path, files: [referenceFile1] }
]);
@@ -483,7 +485,7 @@ namespace ts.projectSystem {
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
openFilesForSession([file1, file2], session);
const compileFileRequest = makeSessionRequest<server.protocol.CompileOnSaveEmitFileRequestArgs>(server.CommandNames.CompileOnSaveEmitFile, { file: file1.path, projectFileName: configFile.path });
const compileFileRequest = makeSessionRequest<server.protocol.CompileOnSaveEmitFileRequestArgs>(CommandNames.CompileOnSaveEmitFile, { file: file1.path, projectFileName: configFile.path });
session.executeCommand(compileFileRequest);
const expectedEmittedFileName = "/a/b/f1.js";
@@ -176,7 +176,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015'",
messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017'",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
+1 -1
View File
@@ -1018,7 +1018,7 @@ import b = require("./moduleB");
const files = [f1, f2, f3, f4];
const names = map(files, f => f.name);
const sourceFiles = arrayToMap(map(files, f => createSourceFile(f.name, f.content, ScriptTarget.ES6)), f => f.fileName);
const sourceFiles = arrayToMap(map(files, f => createSourceFile(f.name, f.content, ScriptTarget.ES2015)), f => f.fileName);
const compilerHost: CompilerHost = {
fileExists : fileName => sourceFiles.has(fileName),
getSourceFile: fileName => sourceFiles.get(fileName),
+4
View File
@@ -253,6 +253,10 @@ var x = 0;`, {
options: { compilerOptions: { allowUnusedLabels: true }, fileName: "input.js", reportDiagnostics: true }
});
transpilesCorrectly("Supports setting 'alwaysStrict'", "x;", {
options: { compilerOptions: { alwaysStrict: true }, fileName: "input.js", reportDiagnostics: true }
});
transpilesCorrectly("Supports setting 'baseUrl'", "x;", {
options: { compilerOptions: { baseUrl: "./folder/baseUrl" }, fileName: "input.js", reportDiagnostics: true }
});
+44 -11
View File
@@ -19,10 +19,8 @@ namespace ts.projectSystem {
export interface PostExecAction {
readonly requestKind: TI.RequestKind;
readonly error: Error;
readonly stdout: string;
readonly stderr: string;
readonly callback: (err: Error, stdout: string, stderr: string) => void;
readonly success: boolean;
readonly callback: TI.RequestCompletedAction;
}
export function notImplemented(): any {
@@ -54,7 +52,7 @@ namespace ts.projectSystem {
export class TestTypingsInstaller extends TI.TypingsInstaller implements server.ITypingsInstaller {
protected projectService: server.ProjectService;
constructor(readonly globalTypingsCacheLocation: string, throttleLimit: number, readonly installTypingHost: server.ServerHost, log?: TI.Log) {
super(globalTypingsCacheLocation, "npm", safeList.path, throttleLimit, log);
super(globalTypingsCacheLocation, safeList.path, throttleLimit, log);
this.init();
}
@@ -65,7 +63,7 @@ namespace ts.projectSystem {
const actionsToRun = this.postExecActions;
this.postExecActions = [];
for (const action of actionsToRun) {
action.callback(action.error, action.stdout, action.stderr);
action.callback(action.success);
}
}
@@ -85,7 +83,7 @@ namespace ts.projectSystem {
return this.installTypingHost;
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: (err: Error, stdout: string, stderr: string) => void): void {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
switch (requestKind) {
case TI.NpmViewRequest:
case TI.NpmInstallRequest:
@@ -108,9 +106,7 @@ namespace ts.projectSystem {
addPostExecAction(requestKind: TI.RequestKind, stdout: string | string[], cb: TI.RequestCompletedAction) {
const out = typeof stdout === "string" ? stdout : createNpmPackageJsonString(stdout);
const action: PostExecAction = {
error: undefined,
stdout: out,
stderr: "",
success: !!out,
callback: cb,
requestKind
};
@@ -139,7 +135,7 @@ namespace ts.projectSystem {
}
export class TestServerEventManager {
private events: server.ProjectServiceEvent[] = [];
public events: server.ProjectServiceEvent[] = [];
handler: server.ProjectServiceEventHandler = (event: server.ProjectServiceEvent) => {
this.events.push(event);
@@ -2281,6 +2277,14 @@ namespace ts.projectSystem {
const session = createSession(host, /*typingsInstaller*/ undefined, serverEventManager.handler);
openFilesForSession([file], session);
serverEventManager.checkEventCountOfType("configFileDiag", 1);
for (const event of serverEventManager.events) {
if (event.eventName === "configFileDiag") {
assert.equal(event.data.configFileName, configFile.path);
assert.equal(event.data.triggerFile, file.path);
return;
}
}
});
it("are generated when the config file doesn't have errors", () => {
@@ -2378,4 +2382,33 @@ namespace ts.projectSystem {
assert.isTrue(errorResult.length === 0);
});
});
describe("non-existing directories listed in config file input array", () => {
it("should be tolerated without crashing the server", () => {
const configFile = {
path: "/a/b/tsconfig.json",
content: `{
"compilerOptions": {},
"include": ["app/*", "test/**/*", "something"]
}`
};
const file1 = {
path: "/a/b/file1.ts",
content: "let t = 10;"
};
const host = createServerHost([file1, configFile]);
const projectService = createProjectService(host);
projectService.openClientFile(file1.path);
host.runQueuedTimeoutCallbacks();
checkNumberOfConfiguredProjects(projectService, 1);
checkNumberOfInferredProjects(projectService, 1);
const configuredProject = projectService.configuredProjects[0];
assert.isTrue(configuredProject.getFileNames().length == 0);
const inferredProject = projectService.inferredProjects[0];
assert.isTrue(inferredProject.containsFile(<server.NormalizedPath>file1.path));
});
});
}
+14 -14
View File
@@ -31,11 +31,11 @@ namespace ts.projectSystem {
function executeCommand(self: Installer, host: TestServerHost, installedTypings: string[], typingFiles: FileOrFolder[], requestKind: TI.RequestKind, cb: TI.RequestCompletedAction): void {
switch (requestKind) {
case TI.NpmInstallRequest:
self.addPostExecAction(requestKind, installedTypings, (err, stdout, stderr) => {
self.addPostExecAction(requestKind, installedTypings, success => {
for (const file of typingFiles) {
host.createFileOrFolder(file, /*createParentDirectory*/ true);
}
cb(err, stdout, stderr);
cb(success);
});
break;
case TI.NpmViewRequest:
@@ -81,7 +81,7 @@ namespace ts.projectSystem {
constructor() {
super(host);
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jquery];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -125,7 +125,7 @@ namespace ts.projectSystem {
constructor() {
super(host);
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jquery];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -221,7 +221,7 @@ namespace ts.projectSystem {
enqueueIsCalled = true;
super.enqueueInstallTypingsRequest(project, typingOptions);
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings = ["@types/jquery"];
const typingFiles = [jquery];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -275,7 +275,7 @@ namespace ts.projectSystem {
constructor() {
super(host);
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings = ["@types/lodash", "@types/react"];
const typingFiles = [lodash, react];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -323,7 +323,7 @@ namespace ts.projectSystem {
enqueueIsCalled = true;
super.enqueueInstallTypingsRequest(project, typingOptions);
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings: string[] = [];
const typingFiles: FileOrFolder[] = [];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -398,7 +398,7 @@ namespace ts.projectSystem {
constructor() {
super(host);
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings = ["@types/commander", "@types/express", "@types/jquery", "@types/moment"];
const typingFiles = [commander, express, jquery, moment];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -477,7 +477,7 @@ namespace ts.projectSystem {
constructor() {
super(host, { throttleLimit: 3 });
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings = ["@types/commander", "@types/express", "@types/jquery", "@types/moment", "@types/lodash"];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
}
@@ -567,10 +567,10 @@ namespace ts.projectSystem {
constructor() {
super(host, { throttleLimit: 3 });
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
if (requestKind === TI.NpmInstallRequest) {
let typingFiles: (FileOrFolder & { typings: string}) [] = [];
if (command.indexOf("commander") >= 0) {
if (args.indexOf("@types/commander") >= 0) {
typingFiles = [commander, jquery, lodash, cordova];
}
else {
@@ -655,7 +655,7 @@ namespace ts.projectSystem {
constructor() {
super(host, { globalTypingsCacheLocation: "/tmp" });
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jqueryDTS];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -701,7 +701,7 @@ namespace ts.projectSystem {
constructor() {
super(host, { globalTypingsCacheLocation: "/tmp" });
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jqueryDTS];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -766,7 +766,7 @@ namespace ts.projectSystem {
constructor() {
super(host, { globalTypingsCacheLocation: "/tmp" }, { isEnabled: () => true, writeLine: msg => messages.push(msg) });
}
runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
assert(false, "runCommand should not be invoked");
}
})();
+1 -1
View File
@@ -201,7 +201,7 @@ interface NumberConstructor {
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
+3
View File
@@ -244,6 +244,9 @@ interface Function {
*/
bind(this: Function, thisArg: any, ...argArray: any[]): any;
/** Returns a string representation of a function. */
toString(): string;
prototype: any;
readonly length: number;
-1
View File
@@ -1,6 +1,5 @@
/// <reference path="..\compiler\commandLineParser.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="protocol.d.ts" />
/// <reference path="session.ts" />
/// <reference types="node" />
-1
View File
@@ -1,7 +1,6 @@
/// <reference path="session.ts" />
namespace ts.server {
export interface SessionClientHost extends LanguageServiceHost {
writeMessage(message: string): void;
}
+7 -8
View File
@@ -1,6 +1,5 @@
/// <reference path="..\compiler\commandLineParser.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="protocol.d.ts" />
/// <reference path="utilities.ts" />
/// <reference path="session.ts" />
/// <reference path="scriptVersionCache.ts"/>
@@ -12,7 +11,7 @@ namespace ts.server {
export const maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;
export type ProjectServiceEvent =
{ eventName: "context", data: { project: Project, fileName: NormalizedPath } } | { eventName: "configFileDiag", data: { triggerFile?: string, configFileName: string, diagnostics: Diagnostic[] } };
{ eventName: "context", data: { project: Project, fileName: NormalizedPath } } | { eventName: "configFileDiag", data: { triggerFile: string, configFileName: string, diagnostics: Diagnostic[] } };
export interface ProjectServiceEventHandler {
(event: ProjectServiceEvent): void;
@@ -394,12 +393,12 @@ namespace ts.server {
this.throttledOperations.schedule(
project.configFileName,
/*delay*/250,
() => this.handleChangeInSourceFileForConfiguredProject(project));
() => this.handleChangeInSourceFileForConfiguredProject(project, fileName));
}
private handleChangeInSourceFileForConfiguredProject(project: ConfiguredProject) {
private handleChangeInSourceFileForConfiguredProject(project: ConfiguredProject, triggerFile: string) {
const { projectOptions, configFileErrors } = this.convertConfigFileContentToProjectOptions(project.configFileName);
this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors);
this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors, triggerFile);
const newRootFiles = projectOptions.files.map((f => this.getCanonicalFileName(f)));
const currentRootFiles = project.getRootFiles().map((f => this.getCanonicalFileName(f)));
@@ -436,7 +435,7 @@ namespace ts.server {
}
const { configFileErrors } = this.convertConfigFileContentToProjectOptions(fileName);
this.reportConfigFileDiagnostics(fileName, configFileErrors);
this.reportConfigFileDiagnostics(fileName, configFileErrors, fileName);
this.logger.info(`Detected newly added tsconfig file: ${fileName}`);
this.reloadProjects();
@@ -712,7 +711,7 @@ namespace ts.server {
Debug.assert(!!parsedCommandLine.fileNames);
if (parsedCommandLine.fileNames.length === 0) {
errors.push(createCompilerDiagnostic(Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename));
(errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename));
return { success: false, configFileErrors: errors };
}
@@ -759,7 +758,7 @@ namespace ts.server {
return project;
}
private reportConfigFileDiagnostics(configFileName: string, diagnostics: Diagnostic[], triggerFile?: string) {
private reportConfigFileDiagnostics(configFileName: string, diagnostics: Diagnostic[], triggerFile: string) {
if (!this.eventHandler) {
return;
}
@@ -1,7 +1,102 @@
/**
* Declaration module describing the TypeScript Server protocol
*/
declare namespace ts.server.protocol {
namespace ts.server.protocol {
export namespace CommandTypes {
export type Brace = "brace";
/* @internal */
export type BraceFull = "brace-full";
export type BraceCompletion = "braceCompletion";
export type Change = "change";
export type Close = "close";
export type Completions = "completions";
/* @internal */
export type CompletionsFull = "completions-full";
export type CompletionDetails = "completionEntryDetails";
export type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList";
export type CompileOnSaveEmitFile = "compileOnSaveEmitFile";
export type Configure = "configure";
export type Definition = "definition";
/* @internal */
export type DefinitionFull = "definition-full";
export type Implementation = "implementation";
/* @internal */
export type ImplementationFull = "implementation-full";
export type Exit = "exit";
export type Format = "format";
export type Formatonkey = "formatonkey";
/* @internal */
export type FormatFull = "format-full";
/* @internal */
export type FormatonkeyFull = "formatonkey-full";
/* @internal */
export type FormatRangeFull = "formatRange-full";
export type Geterr = "geterr";
export type GeterrForProject = "geterrForProject";
export type SemanticDiagnosticsSync = "semanticDiagnosticsSync";
export type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync";
export type NavBar = "navbar";
/* @internal */
export type NavBarFull = "navbar-full";
export type Navto = "navto";
/* @internal */
export type NavtoFull = "navto-full";
export type NavTree = "navtree";
export type NavTreeFull = "navtree-full";
export type Occurrences = "occurrences";
export type DocumentHighlights = "documentHighlights";
/* @internal */
export type DocumentHighlightsFull = "documentHighlights-full";
export type Open = "open";
export type Quickinfo = "quickinfo";
/* @internal */
export type QuickinfoFull = "quickinfo-full";
export type References = "references";
/* @internal */
export type ReferencesFull = "references-full";
export type Reload = "reload";
export type Rename = "rename";
/* @internal */
export type RenameInfoFull = "rename-full";
/* @internal */
export type RenameLocationsFull = "renameLocations-full";
export type Saveto = "saveto";
export type SignatureHelp = "signatureHelp";
/* @internal */
export type SignatureHelpFull = "signatureHelp-full";
export type TypeDefinition = "typeDefinition";
export type ProjectInfo = "projectInfo";
export type ReloadProjects = "reloadProjects";
export type Unknown = "unknown";
export type OpenExternalProject = "openExternalProject";
export type OpenExternalProjects = "openExternalProjects";
export type CloseExternalProject = "closeExternalProject";
/* @internal */
export type SynchronizeProjectList = "synchronizeProjectList";
/* @internal */
export type ApplyChangedToOpenFiles = "applyChangedToOpenFiles";
/* @internal */
export type EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full";
/* @internal */
export type Cleanup = "cleanup";
/* @internal */
export type OutliningSpans = "outliningSpans";
export type TodoComments = "todoComments";
export type Indentation = "indentation";
export type DocCommentTemplate = "docCommentTemplate";
/* @internal */
export type CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full";
/* @internal */
export type NameOrDottedNameSpan = "nameOrDottedNameSpan";
/* @internal */
export type BreakpointStatement = "breakpointStatement";
export type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects";
export type GetCodeFixes = "getCodeFixes";
/* @internal */
export type GetCodeFixesFull = "getCodeFixes-full";
export type GetSupportedCodeFixes = "getSupportedCodeFixes";
}
/**
* A TypeScript Server message
*/
@@ -36,6 +131,7 @@ declare namespace ts.server.protocol {
* Request to reload the project structure for all the opened files
*/
export interface ReloadProjectsRequest extends Message {
command: CommandTypes.ReloadProjects;
}
/**
@@ -98,10 +194,25 @@ declare namespace ts.server.protocol {
projectFileName?: string;
}
/**
* Requests a JS Doc comment template for a given position
*/
export interface DocCommentTemplateRequest extends FileLocationRequest {
command: CommandTypes.DocCommentTemplate;
}
/**
* Response to DocCommentTemplateRequest
*/
export interface DocCommandTemplateResponse extends Response {
body?: TextInsertion;
}
/**
* A request to get TODO comments from the file
*/
export interface TodoCommentRequest extends FileRequest {
command: CommandTypes.TodoComments;
arguments: TodoCommentRequestArgs;
}
@@ -115,13 +226,58 @@ declare namespace ts.server.protocol {
descriptors: TodoCommentDescriptor[];
}
/**
* Response for TodoCommentRequest request.
*/
export interface TodoCommentsResponse extends Response {
body?: TodoComment[];
}
/**
* Request to obtain outlining spans in file.
*/
/* @internal */
export interface OutliningSpansRequest extends FileRequest {
command: CommandTypes.OutliningSpans;
}
/**
* Response to OutliningSpansRequest request.
*/
/* @internal */
export interface OutliningSpansResponse extends Response {
body?: OutliningSpan[];
}
/**
* A request to get indentation for a location in file
*/
export interface IndentationRequest extends FileLocationRequest {
command: CommandTypes.Indentation;
arguments: IndentationRequestArgs;
}
/**
* Response for IndentationRequest request.
*/
export interface IndentationResponse extends Response {
body?: IndentationResult;
}
/**
* Indentation result representing where indentation should be placed
*/
export interface IndentationResult {
/**
* The base position in the document that the indent should be relative to
*/
position: number;
/**
* The number of columns the indent should be at relative to the position's column.
*/
indentation: number;
}
/**
* Arguments for IndentationRequest request.
*/
@@ -147,6 +303,7 @@ declare namespace ts.server.protocol {
* A request to get the project information of the current file.
*/
export interface ProjectInfoRequest extends Request {
command: CommandTypes.ProjectInfo;
arguments: ProjectInfoRequestArgs;
}
@@ -223,16 +380,17 @@ declare namespace ts.server.protocol {
/**
* The line number for the request (1-based).
*/
line?: number;
line: number;
/**
* The character offset (on the line) for the request (1-based).
*/
offset?: number;
offset: number;
/**
* Position (can be specified instead of line/offset pair)
*/
/* @internal */
position?: number;
}
@@ -240,6 +398,7 @@ declare namespace ts.server.protocol {
* Request for the available codefixes at a specific position.
*/
export interface CodeFixRequest extends Request {
command: CommandTypes.GetCodeFixes;
arguments: CodeFixRequestArgs;
}
@@ -250,31 +409,33 @@ declare namespace ts.server.protocol {
/**
* The line number for the request (1-based).
*/
startLine?: number;
startLine: number;
/**
* The character offset (on the line) for the request (1-based).
*/
startOffset?: number;
startOffset: number;
/**
* Position (can be specified instead of line/offset pair)
*/
/* @internal */
startPosition?: number;
/**
* The line number for the request (1-based).
*/
endLine?: number;
endLine: number;
/**
* The character offset (on the line) for the request (1-based).
*/
endOffset?: number;
endOffset: number;
/**
* Position (can be specified instead of line/offset pair)
*/
/* @internal */
endPosition?: number;
/**
@@ -283,6 +444,13 @@ declare namespace ts.server.protocol {
errorCodes?: number[];
}
/**
* Response for GetCodeFixes request.
*/
export interface GetCodeFixesResponse extends Response {
body?: CodeAction[];
}
/**
* A request whose arguments specify a file location (file, line, col).
*/
@@ -291,16 +459,34 @@ declare namespace ts.server.protocol {
}
/**
* A request to get semantic diagnostics for a span in the file
* A request to get codes of supported code fixes.
*/
export interface SemanticDiagnosticsRequest extends FileRequest {
arguments: SemanticDiagnosticsRequestArgs;
export interface GetSupportedCodeFixesRequest extends Request {
command: CommandTypes.GetSupportedCodeFixes;
}
/**
* Arguments for SemanticDiagnosticsRequest request.
* A response for GetSupportedCodeFixesRequest request.
*/
export interface SemanticDiagnosticsRequestArgs extends FileRequestArgs {
export interface GetSupportedCodeFixesResponse extends Response {
/**
* List of error codes supported by the server.
*/
body?: string[];
}
/**
* A request to get encoded semantic classifications for a span in the file
*/
/** @internal */
export interface EncodedSemanticClassificationsRequest extends FileRequest {
arguments: EncodedSemanticClassificationsRequestArgs;
}
/**
* Arguments for EncodedSemanticClassificationsRequest request.
*/
export interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs {
/**
* Start position of the span.
*/
@@ -328,6 +514,7 @@ declare namespace ts.server.protocol {
* define the symbol found in file at location line, col.
*/
export interface DefinitionRequest extends FileLocationRequest {
command: CommandTypes.Definition;
}
/**
@@ -336,6 +523,7 @@ declare namespace ts.server.protocol {
* define the type for the symbol found in file at location line, col.
*/
export interface TypeDefinitionRequest extends FileLocationRequest {
command: CommandTypes.TypeDefinition;
}
/**
@@ -344,6 +532,7 @@ declare namespace ts.server.protocol {
* implement the symbol found in file at location line, col.
*/
export interface ImplementationRequest extends FileLocationRequest {
command: CommandTypes.Implementation;
}
/**
@@ -404,6 +593,7 @@ declare namespace ts.server.protocol {
* Request to get brace completion for a location in the file.
*/
export interface BraceCompletionRequest extends FileLocationRequest {
command: CommandTypes.BraceCompletion;
arguments: BraceCompletionRequestArgs;
}
@@ -423,6 +613,7 @@ declare namespace ts.server.protocol {
* in the file at a given line and column.
*/
export interface OccurrencesRequest extends FileLocationRequest {
command: CommandTypes.Occurrences;
}
export interface OccurrencesResponseItem extends FileSpan {
@@ -442,6 +633,7 @@ declare namespace ts.server.protocol {
* in the file at a given line and column.
*/
export interface DocumentHighlightsRequest extends FileLocationRequest {
command: CommandTypes.DocumentHighlights;
arguments: DocumentHighlightsRequestArgs;
}
@@ -481,6 +673,7 @@ declare namespace ts.server.protocol {
* reference the symbol found in file at location line, col.
*/
export interface ReferencesRequest extends FileLocationRequest {
command: CommandTypes.References;
}
export interface ReferencesResponseItem extends FileSpan {
@@ -555,6 +748,7 @@ declare namespace ts.server.protocol {
* name of the symbol so that client can print it unambiguously.
*/
export interface RenameRequest extends FileLocationRequest {
command: CommandTypes.Rename;
arguments: RenameRequestArgs;
}
@@ -754,6 +948,7 @@ declare namespace ts.server.protocol {
/**
* Represents set of changes in open file
*/
/* @internal */
export interface ChangedOpenFile {
/**
* Name of file
@@ -765,65 +960,6 @@ declare namespace ts.server.protocol {
changes: ts.TextChange[];
}
/**
* Editor options
*/
export interface EditorOptions {
/** Number of spaces for each tab. Default value is 4. */
tabSize?: number;
/** Number of spaces to indent during formatting. Default value is 4. */
indentSize?: number;
/** Number of additional spaces to indent during formatting to preserve base indentation (ex. script block indentation). Default value is 0. */
baseIndentSize?: number;
/** The new line character to be used. Default value is the OS line delimiter. */
newLineCharacter?: string;
/** Whether tabs should be converted to spaces. Default value is true. */
convertTabsToSpaces?: boolean;
}
/**
* Format options
*/
export interface FormatOptions extends EditorOptions {
/** Defines space handling after a comma delimiter. Default value is true. */
insertSpaceAfterCommaDelimiter?: boolean;
/** Defines space handling after a semicolon in a for statement. Default value is true */
insertSpaceAfterSemicolonInForStatements?: boolean;
/** Defines space handling after a binary operator. Default value is true. */
insertSpaceBeforeAndAfterBinaryOperators?: boolean;
/** Defines space handling after keywords in control flow statement. Default value is true. */
insertSpaceAfterKeywordsInControlFlowStatements?: boolean;
/** Defines space handling after function keyword for anonymous functions. Default value is false. */
insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean;
/** Defines space handling after opening and before closing non empty parenthesis. Default value is false. */
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean;
/** Defines space handling after opening and before closing non empty brackets. Default value is false. */
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean;
/** Defines space handling before and after template string braces. Default value is false. */
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean;
/** Defines space handling before and after JSX expression braces. Default value is false. */
insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean;
/** Defines whether an open brace is put onto a new line for functions or not. Default value is false. */
placeOpenBraceOnNewLineForFunctions?: boolean;
/** Defines whether an open brace is put onto a new line for control blocks or not. Default value is false. */
placeOpenBraceOnNewLineForControlBlocks?: boolean;
}
/**
* Information found in a configure request.
@@ -844,12 +980,7 @@ declare namespace ts.server.protocol {
/**
* The format options to use during formatting and other code editing features.
*/
formatOptions?: FormatOptions;
/**
* If set to true - then all loose files will land into one inferred project
*/
useOneInferredProject?: boolean;
formatOptions?: FormatCodeSettings;
}
/**
@@ -857,6 +988,7 @@ declare namespace ts.server.protocol {
* host information, such as host type, tab size, and indent size.
*/
export interface ConfigureRequest extends Request {
command: CommandTypes.Configure;
arguments: ConfigureRequestArguments;
}
@@ -892,6 +1024,7 @@ declare namespace ts.server.protocol {
* send a response to an open request.
*/
export interface OpenRequest extends Request {
command: CommandTypes.Open;
arguments: OpenRequestArgs;
}
@@ -899,18 +1032,20 @@ declare namespace ts.server.protocol {
* Request to open or update external project
*/
export interface OpenExternalProjectRequest extends Request {
command: CommandTypes.OpenExternalProject;
arguments: OpenExternalProjectArgs;
}
/**
* Arguments to OpenExternalProjectRequest request
*/
type OpenExternalProjectArgs = ExternalProject;
export type OpenExternalProjectArgs = ExternalProject;
/**
* Request to open multiple external projects
*/
export interface OpenExternalProjectsRequest extends Request {
command: CommandTypes.OpenExternalProjects;
arguments: OpenExternalProjectsArgs;
}
@@ -924,10 +1059,25 @@ declare namespace ts.server.protocol {
projects: ExternalProject[];
}
/**
* Response to OpenExternalProjectRequest request. This is just an acknowledgement, so
* no body field is required.
*/
export interface OpenExternalProjectResponse extends Response {
}
/**
* Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so
* no body field is required.
*/
export interface OpenExternalProjectsResponse extends Response {
}
/**
* Request to close external project.
*/
export interface CloseExternalProjectRequest extends Request {
command: CommandTypes.CloseExternalProject;
arguments: CloseExternalProjectRequestArgs;
}
@@ -941,9 +1091,17 @@ declare namespace ts.server.protocol {
projectFileName: string;
}
/**
* Response to CloseExternalProjectRequest request. This is just an acknowledgement, so
* no body field is required.
*/
export interface CloseExternalProjectResponse extends Response {
}
/**
* Request to check if given list of projects is up-to-date and synchronize them if necessary
*/
/* @internal */
export interface SynchronizeProjectListRequest extends Request {
arguments: SynchronizeProjectListRequestArgs;
}
@@ -961,6 +1119,7 @@ declare namespace ts.server.protocol {
/**
* Request to synchronize list of open files with the client
*/
/* @internal */
export interface ApplyChangedToOpenFilesRequest extends Request {
arguments: ApplyChangedToOpenFilesRequestArgs;
}
@@ -968,6 +1127,7 @@ declare namespace ts.server.protocol {
/**
* Arguments to ApplyChangedToOpenFilesRequest
*/
/* @internal */
export interface ApplyChangedToOpenFilesRequestArgs {
/**
* List of newly open files
@@ -993,6 +1153,7 @@ declare namespace ts.server.protocol {
* or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true.
*/
export interface SetCompilerOptionsForInferredProjectsRequest extends Request {
command: CommandTypes.CompilerOptionsForInferredProjects;
arguments: SetCompilerOptionsForInferredProjectsArgs;
}
@@ -1006,11 +1167,19 @@ declare namespace ts.server.protocol {
options: ExternalProjectCompilerOptions;
}
/**
* Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so
* no body field is required.
*/
export interface SetCompilerOptionsForInferredProjectsResponse extends Response {
}
/**
* Exit request; value of command field is "exit". Ask the server process
* to exit.
*/
export interface ExitRequest extends Request {
command: CommandTypes.Exit;
}
/**
@@ -1021,6 +1190,7 @@ declare namespace ts.server.protocol {
* currently send a response to a close request.
*/
export interface CloseRequest extends FileRequest {
command: CommandTypes.Close;
}
/**
@@ -1028,6 +1198,7 @@ declare namespace ts.server.protocol {
* NOTE: this us query-only operation and does not generate any output on disk.
*/
export interface CompileOnSaveAffectedFileListRequest extends FileRequest {
command: CommandTypes.CompileOnSaveAffectedFileList;
}
/**
@@ -1055,7 +1226,8 @@ declare namespace ts.server.protocol {
* Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk.
*/
export interface CompileOnSaveEmitFileRequest extends FileRequest {
args: CompileOnSaveEmitFileRequestArgs;
command: CommandTypes.CompileOnSaveEmitFile;
arguments: CompileOnSaveEmitFileRequestArgs;
}
/**
@@ -1075,6 +1247,7 @@ declare namespace ts.server.protocol {
* line, col.
*/
export interface QuickInfoRequest extends FileLocationRequest {
command: CommandTypes.Quickinfo;
}
/**
@@ -1136,12 +1309,12 @@ declare namespace ts.server.protocol {
/**
* End position of the range for which to format text in file.
*/
/* @internal */
endPosition?: number;
/**
* Format options to be used.
*/
options?: ts.FormatCodeOptions;
options?: FormatCodeSettings;
}
/**
@@ -1152,6 +1325,7 @@ declare namespace ts.server.protocol {
* reformatted text.
*/
export interface FormatRequest extends FileLocationRequest {
command: CommandTypes.Format;
arguments: FormatRequestArgs;
}
@@ -1213,7 +1387,7 @@ declare namespace ts.server.protocol {
*/
key: string;
options?: ts.FormatCodeOptions;
options?: FormatCodeSettings;
}
/**
@@ -1225,6 +1399,7 @@ declare namespace ts.server.protocol {
* reformatted text.
*/
export interface FormatOnKeyRequest extends FileLocationRequest {
command: CommandTypes.Formatonkey;
arguments: FormatOnKeyRequestArgs;
}
@@ -1245,6 +1420,7 @@ declare namespace ts.server.protocol {
* begin with prefix.
*/
export interface CompletionsRequest extends FileLocationRequest {
command: CommandTypes.Completions;
arguments: CompletionsRequestArgs;
}
@@ -1265,6 +1441,7 @@ declare namespace ts.server.protocol {
* detailed information for each completion entry.
*/
export interface CompletionDetailsRequest extends FileLocationRequest {
command: CommandTypes.CompletionDetails;
arguments: CompletionDetailsRequestArgs;
}
@@ -1451,6 +1628,7 @@ declare namespace ts.server.protocol {
* help.
*/
export interface SignatureHelpRequest extends FileLocationRequest {
command: CommandTypes.SignatureHelp;
arguments: SignatureHelpRequestArgs;
}
@@ -1465,6 +1643,7 @@ declare namespace ts.server.protocol {
* Synchronous request for semantic diagnostics of one file.
*/
export interface SemanticDiagnosticsSyncRequest extends FileRequest {
command: CommandTypes.SemanticDiagnosticsSync;
arguments: SemanticDiagnosticsSyncRequestArgs;
}
@@ -1483,6 +1662,7 @@ declare namespace ts.server.protocol {
* Synchronous request for syntactic diagnostics of one file.
*/
export interface SyntacticDiagnosticsSyncRequest extends FileRequest {
command: CommandTypes.SyntacticDiagnosticsSync;
arguments: SyntacticDiagnosticsSyncRequestArgs;
}
@@ -1519,6 +1699,7 @@ declare namespace ts.server.protocol {
* it request for every file in this project.
*/
export interface GeterrForProjectRequest extends Request {
command: CommandTypes.GeterrForProject;
arguments: GeterrForProjectRequestArgs;
}
@@ -1550,6 +1731,7 @@ declare namespace ts.server.protocol {
* file that is currently visible, in most-recently-used order.
*/
export interface GeterrRequest extends Request {
command: CommandTypes.Geterr;
arguments: GeterrRequestArgs;
}
@@ -1642,11 +1824,12 @@ declare namespace ts.server.protocol {
* The two names can be identical.
*/
export interface ReloadRequest extends FileRequest {
command: CommandTypes.Reload;
arguments: ReloadRequestArgs;
}
/**
* Response to "reload" request. This is just an acknowledgement, so
* Response to "reload" request. This is just an acknowledgement, so
* no body field is required.
*/
export interface ReloadResponse extends Response {
@@ -1671,6 +1854,7 @@ declare namespace ts.server.protocol {
* "saveto" request.
*/
export interface SavetoRequest extends FileRequest {
command: CommandTypes.Saveto;
arguments: SavetoRequestArgs;
}
@@ -1703,6 +1887,7 @@ declare namespace ts.server.protocol {
* context for the search is given by the named file.
*/
export interface NavtoRequest extends FileRequest {
command: CommandTypes.Navto;
arguments: NavtoRequestArgs;
}
@@ -1786,6 +1971,7 @@ declare namespace ts.server.protocol {
* Server does not currently send a response to a change request.
*/
export interface ChangeRequest extends FileLocationRequest {
command: CommandTypes.Change;
arguments: ChangeRequestArgs;
}
@@ -1802,6 +1988,7 @@ declare namespace ts.server.protocol {
* found in file at location line, offset.
*/
export interface BraceRequest extends FileLocationRequest {
command: CommandTypes.Brace;
}
/**
@@ -1810,6 +1997,7 @@ declare namespace ts.server.protocol {
* extracted from the requested file.
*/
export interface NavBarRequest extends FileRequest {
command: CommandTypes.NavBar;
}
/**
@@ -1817,6 +2005,7 @@ declare namespace ts.server.protocol {
* Return response giving the navigation tree of the requested file.
*/
export interface NavTreeRequest extends FileRequest {
command: CommandTypes.NavTree;
}
export interface NavigationBarItem {
+1 -1
View File
@@ -91,7 +91,7 @@ namespace ts.server {
return this.containingProjects[0];
}
setFormatOptions(formatSettings: protocol.FormatOptions): void {
setFormatOptions(formatSettings: FormatCodeSettings): void {
if (formatSettings) {
if (!this.formatCodeSettings) {
this.formatCodeSettings = getDefaultFormatCodeSettings(this.host);
-1
View File
@@ -1,6 +1,5 @@
/// <reference path="..\compiler\commandLineParser.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="protocol.d.ts" />
/// <reference path="session.ts" />
namespace ts.server {
+6 -1
View File
@@ -265,13 +265,16 @@ namespace ts.server {
installerEventPort: number,
canUseEvents: boolean,
useSingleInferredProject: boolean,
disableAutomaticTypingAcquisition: boolean,
globalTypingsCacheLocation: string,
logger: server.Logger) {
super(
host,
cancellationToken,
useSingleInferredProject,
new NodeTypingsInstaller(logger, installerEventPort, globalTypingsCacheLocation, host.newLine),
disableAutomaticTypingAcquisition
? nullTypingsInstaller
: new NodeTypingsInstaller(logger, installerEventPort, globalTypingsCacheLocation, host.newLine),
Buffer.byteLength,
process.hrtime,
logger,
@@ -512,12 +515,14 @@ namespace ts.server {
}
const useSingleInferredProject = sys.args.indexOf("--useSingleInferredProject") >= 0;
const disableAutomaticTypingAcquisition = sys.args.indexOf("--disableAutomaticTypingAcquisition") >= 0;
const ioSession = new IOSession(
sys,
cancellationToken,
eventPort,
/*canUseEvents*/ eventPort === undefined,
useSingleInferredProject,
disableAutomaticTypingAcquisition,
getGlobalTypingsCacheLocation(),
logger);
process.on("uncaughtException", function (err: Error) {
+76 -75
View File
@@ -1,6 +1,6 @@
/// <reference path="..\compiler\commandLineParser.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="protocol.d.ts" />
/// <reference path="protocol.ts" />
/// <reference path="editorServices.ts" />
namespace ts.server {
@@ -83,74 +83,74 @@ namespace ts.server {
}
export namespace CommandNames {
export const Brace = "brace";
export const BraceFull = "brace-full";
export const BraceCompletion = "braceCompletion";
export const Change = "change";
export const Close = "close";
export const Completions = "completions";
export const CompletionsFull = "completions-full";
export const CompletionDetails = "completionEntryDetails";
export const CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList";
export const CompileOnSaveEmitFile = "compileOnSaveEmitFile";
export const Configure = "configure";
export const Definition = "definition";
export const DefinitionFull = "definition-full";
export const Exit = "exit";
export const Format = "format";
export const Formatonkey = "formatonkey";
export const FormatFull = "format-full";
export const FormatonkeyFull = "formatonkey-full";
export const FormatRangeFull = "formatRange-full";
export const Geterr = "geterr";
export const GeterrForProject = "geterrForProject";
export const Implementation = "implementation";
export const ImplementationFull = "implementation-full";
export const SemanticDiagnosticsSync = "semanticDiagnosticsSync";
export const SyntacticDiagnosticsSync = "syntacticDiagnosticsSync";
export const NavBar = "navbar";
export const NavBarFull = "navbar-full";
export const NavTree = "navtree";
export const NavTreeFull = "navtree-full";
export const Navto = "navto";
export const NavtoFull = "navto-full";
export const Occurrences = "occurrences";
export const DocumentHighlights = "documentHighlights";
export const DocumentHighlightsFull = "documentHighlights-full";
export const Open = "open";
export const Quickinfo = "quickinfo";
export const QuickinfoFull = "quickinfo-full";
export const References = "references";
export const ReferencesFull = "references-full";
export const Reload = "reload";
export const Rename = "rename";
export const RenameInfoFull = "rename-full";
export const RenameLocationsFull = "renameLocations-full";
export const Saveto = "saveto";
export const SignatureHelp = "signatureHelp";
export const SignatureHelpFull = "signatureHelp-full";
export const TypeDefinition = "typeDefinition";
export const ProjectInfo = "projectInfo";
export const ReloadProjects = "reloadProjects";
export const Unknown = "unknown";
export const OpenExternalProject = "openExternalProject";
export const OpenExternalProjects = "openExternalProjects";
export const CloseExternalProject = "closeExternalProject";
export const SynchronizeProjectList = "synchronizeProjectList";
export const ApplyChangedToOpenFiles = "applyChangedToOpenFiles";
export const EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full";
export const Cleanup = "cleanup";
export const OutliningSpans = "outliningSpans";
export const TodoComments = "todoComments";
export const Indentation = "indentation";
export const DocCommentTemplate = "docCommentTemplate";
export const CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full";
export const NameOrDottedNameSpan = "nameOrDottedNameSpan";
export const BreakpointStatement = "breakpointStatement";
export const CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects";
export const GetCodeFixes = "getCodeFixes";
export const GetCodeFixesFull = "getCodeFixes-full";
export const GetSupportedCodeFixes = "getSupportedCodeFixes";
export const Brace: protocol.CommandTypes.Brace = "brace";
export const BraceFull: protocol.CommandTypes.BraceFull = "brace-full";
export const BraceCompletion: protocol.CommandTypes.BraceCompletion = "braceCompletion";
export const Change: protocol.CommandTypes.Change = "change";
export const Close: protocol.CommandTypes.Close = "close";
export const Completions: protocol.CommandTypes.Completions = "completions";
export const CompletionsFull: protocol.CommandTypes.CompletionsFull = "completions-full";
export const CompletionDetails: protocol.CommandTypes.CompletionDetails = "completionEntryDetails";
export const CompileOnSaveAffectedFileList: protocol.CommandTypes.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList";
export const CompileOnSaveEmitFile: protocol.CommandTypes.CompileOnSaveEmitFile = "compileOnSaveEmitFile";
export const Configure: protocol.CommandTypes.Configure = "configure";
export const Definition: protocol.CommandTypes.Definition = "definition";
export const DefinitionFull: protocol.CommandTypes.DefinitionFull = "definition-full";
export const Exit: protocol.CommandTypes.Exit = "exit";
export const Format: protocol.CommandTypes.Format = "format";
export const Formatonkey: protocol.CommandTypes.Formatonkey = "formatonkey";
export const FormatFull: protocol.CommandTypes.FormatFull = "format-full";
export const FormatonkeyFull: protocol.CommandTypes.FormatonkeyFull = "formatonkey-full";
export const FormatRangeFull: protocol.CommandTypes.FormatRangeFull = "formatRange-full";
export const Geterr: protocol.CommandTypes.Geterr = "geterr";
export const GeterrForProject: protocol.CommandTypes.GeterrForProject = "geterrForProject";
export const Implementation: protocol.CommandTypes.Implementation = "implementation";
export const ImplementationFull: protocol.CommandTypes.ImplementationFull = "implementation-full";
export const SemanticDiagnosticsSync: protocol.CommandTypes.SemanticDiagnosticsSync = "semanticDiagnosticsSync";
export const SyntacticDiagnosticsSync: protocol.CommandTypes.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync";
export const NavBar: protocol.CommandTypes.NavBar = "navbar";
export const NavBarFull: protocol.CommandTypes.NavBarFull = "navbar-full";
export const NavTree: protocol.CommandTypes.NavTree = "navtree";
export const NavTreeFull: protocol.CommandTypes.NavTreeFull = "navtree-full";
export const Navto: protocol.CommandTypes.Navto = "navto";
export const NavtoFull: protocol.CommandTypes.NavtoFull = "navto-full";
export const Occurrences: protocol.CommandTypes.Occurrences = "occurrences";
export const DocumentHighlights: protocol.CommandTypes.DocumentHighlights = "documentHighlights";
export const DocumentHighlightsFull: protocol.CommandTypes.DocumentHighlightsFull = "documentHighlights-full";
export const Open: protocol.CommandTypes.Open = "open";
export const Quickinfo: protocol.CommandTypes.Quickinfo = "quickinfo";
export const QuickinfoFull: protocol.CommandTypes.QuickinfoFull = "quickinfo-full";
export const References: protocol.CommandTypes.References = "references";
export const ReferencesFull: protocol.CommandTypes.ReferencesFull = "references-full";
export const Reload: protocol.CommandTypes.Reload = "reload";
export const Rename: protocol.CommandTypes.Rename = "rename";
export const RenameInfoFull: protocol.CommandTypes.RenameInfoFull = "rename-full";
export const RenameLocationsFull: protocol.CommandTypes.RenameLocationsFull = "renameLocations-full";
export const Saveto: protocol.CommandTypes.Saveto = "saveto";
export const SignatureHelp: protocol.CommandTypes.SignatureHelp = "signatureHelp";
export const SignatureHelpFull: protocol.CommandTypes.SignatureHelpFull = "signatureHelp-full";
export const TypeDefinition: protocol.CommandTypes.TypeDefinition = "typeDefinition";
export const ProjectInfo: protocol.CommandTypes.ProjectInfo = "projectInfo";
export const ReloadProjects: protocol.CommandTypes.ReloadProjects = "reloadProjects";
export const Unknown: protocol.CommandTypes.Unknown = "unknown";
export const OpenExternalProject: protocol.CommandTypes.OpenExternalProject = "openExternalProject";
export const OpenExternalProjects: protocol.CommandTypes.OpenExternalProjects = "openExternalProjects";
export const CloseExternalProject: protocol.CommandTypes.CloseExternalProject = "closeExternalProject";
export const SynchronizeProjectList: protocol.CommandTypes.SynchronizeProjectList = "synchronizeProjectList";
export const ApplyChangedToOpenFiles: protocol.CommandTypes.ApplyChangedToOpenFiles = "applyChangedToOpenFiles";
export const EncodedSemanticClassificationsFull: protocol.CommandTypes.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full";
export const Cleanup: protocol.CommandTypes.Cleanup = "cleanup";
export const OutliningSpans: protocol.CommandTypes.OutliningSpans = "outliningSpans";
export const TodoComments: protocol.CommandTypes.TodoComments = "todoComments";
export const Indentation: protocol.CommandTypes.Indentation = "indentation";
export const DocCommentTemplate: protocol.CommandTypes.DocCommentTemplate = "docCommentTemplate";
export const CompilerOptionsDiagnosticsFull: protocol.CommandTypes.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full";
export const NameOrDottedNameSpan: protocol.CommandTypes.NameOrDottedNameSpan = "nameOrDottedNameSpan";
export const BreakpointStatement: protocol.CommandTypes.BreakpointStatement = "breakpointStatement";
export const CompilerOptionsForInferredProjects: protocol.CommandTypes.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects";
export const GetCodeFixes: protocol.CommandTypes.GetCodeFixes = "getCodeFixes";
export const GetCodeFixesFull: protocol.CommandTypes.GetCodeFixesFull = "getCodeFixes-full";
export const GetSupportedCodeFixes: protocol.CommandTypes.GetSupportedCodeFixes = "getSupportedCodeFixes";
}
export function formatMessage<T extends protocol.Message>(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string {
@@ -363,7 +363,7 @@ namespace ts.server {
}
}
private getEncodedSemanticClassifications(args: protocol.SemanticDiagnosticsRequestArgs) {
private getEncodedSemanticClassifications(args: protocol.EncodedSemanticClassificationsRequestArgs) {
const { file, project } = this.getFileAndProject(args);
return project.getLanguageService().getEncodedSemanticClassifications(file, args);
}
@@ -761,7 +761,7 @@ namespace ts.server {
if (this.eventHander) {
this.eventHander({
eventName: "configFileDiag",
data: { fileName, configFileName, diagnostics: configFileErrors || [] }
data: { triggerFile: fileName, configFileName, diagnostics: configFileErrors || [] }
});
}
}
@@ -967,7 +967,7 @@ namespace ts.server {
result.push({ name, kind, kindModifiers, sortText, replacementSpan: convertedSpan });
}
return result;
}, []).sort((a, b) => a.name.localeCompare(b.name));
}, []).sort((a, b) => ts.compareStrings(a.name, b.name));
}
else {
return completions;
@@ -1470,7 +1470,7 @@ namespace ts.server {
[CommandNames.BraceCompletion]: (request: protocol.BraceCompletionRequest) => {
return this.requiredResponse(this.isValidBraceCompletion(request.arguments));
},
[CommandNames.DocCommentTemplate]: (request: protocol.FileLocationRequest) => {
[CommandNames.DocCommentTemplate]: (request: protocol.DocCommentTemplateRequest) => {
return this.requiredResponse(this.getDocCommentTemplate(request.arguments));
},
[CommandNames.Format]: (request: protocol.FormatRequest) => {
@@ -1512,7 +1512,7 @@ namespace ts.server {
[CommandNames.CompilerOptionsDiagnosticsFull]: (request: protocol.CompilerOptionsDiagnosticsRequest) => {
return this.requiredResponse(this.getCompilerOptionsDiagnostics(request.arguments));
},
[CommandNames.EncodedSemanticClassificationsFull]: (request: protocol.SemanticDiagnosticsRequest) => {
[CommandNames.EncodedSemanticClassificationsFull]: (request: protocol.EncodedSemanticClassificationsRequest) => {
return this.requiredResponse(this.getEncodedSemanticClassifications(request.arguments));
},
[CommandNames.Cleanup]: (request: protocol.Request) => {
@@ -1590,7 +1590,8 @@ namespace ts.server {
return this.requiredResponse(this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ false));
},
[CommandNames.CompilerOptionsForInferredProjects]: (request: protocol.SetCompilerOptionsForInferredProjectsRequest) => {
return this.requiredResponse(this.setCompilerOptionsForInferredProjects(request.arguments));
this.setCompilerOptionsForInferredProjects(request.arguments);
return this.requiredResponse(true);
},
[CommandNames.ProjectInfo]: (request: protocol.ProjectInfoRequest) => {
return this.requiredResponse(this.getProjectInfo(request.arguments));
+1 -1
View File
@@ -22,7 +22,7 @@
"typingsCache.ts",
"project.ts",
"editorServices.ts",
"protocol.d.ts",
"protocol.ts",
"session.ts",
"server.ts"
]
@@ -33,23 +33,38 @@ namespace ts.server.typingsInstaller {
}
}
export class NodeTypingsInstaller extends TypingsInstaller {
private readonly exec: { (command: string, options: { cwd: string }, callback?: (error: Error, stdout: string, stderr: string) => void): any };
type HttpGet = {
(url: string, callback: (response: HttpResponse) => void): NodeJS.EventEmitter;
};
interface HttpResponse extends NodeJS.ReadableStream {
statusCode: number;
statusMessage: string;
destroy(): void;
}
type Exec = {
(command: string, options: { cwd: string }, callback?: (error: Error, stdout: string, stderr: string) => void): any
};
export class NodeTypingsInstaller extends TypingsInstaller {
private readonly exec: Exec;
private readonly httpGet: HttpGet;
private readonly npmPath: string;
readonly installTypingHost: InstallTypingHost = sys;
constructor(globalTypingsCacheLocation: string, throttleLimit: number, log: Log) {
super(
globalTypingsCacheLocation,
/*npmPath*/ getNPMLocation(process.argv[0]),
toPath("typingSafeList.json", __dirname, createGetCanonicalFileName(sys.useCaseSensitiveFileNames)),
throttleLimit,
log);
if (this.log.isEnabled()) {
this.log.writeLine(`Process id: ${process.pid}`);
}
const { exec } = require("child_process");
this.exec = exec;
this.npmPath = getNPMLocation(process.argv[0]);
this.exec = require("child_process").exec;
this.httpGet = require("http").get;
}
init() {
@@ -75,17 +90,54 @@ namespace ts.server.typingsInstaller {
}
}
protected runCommand(requestKind: RequestKind, requestId: number, command: string, cwd: string, onRequestCompleted: RequestCompletedAction): void {
protected executeRequest(requestKind: RequestKind, requestId: number, args: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void {
if (this.log.isEnabled()) {
this.log.writeLine(`#${requestId} running command '${command}'.`);
this.log.writeLine(`#${requestId} executing ${requestKind}, arguments'${JSON.stringify(args)}'.`);
}
switch (requestKind) {
case NpmViewRequest: {
// const command = `${self.npmPath} view @types/${typing} --silent name`;
// use http request to global npm registry instead of running npm view
Debug.assert(args.length === 1);
const url = `http://registry.npmjs.org/@types%2f${args[0]}`;
const start = Date.now();
this.httpGet(url, response => {
let ok = false;
if (this.log.isEnabled()) {
this.log.writeLine(`${requestKind} #${requestId} request to ${url}:: status code ${response.statusCode}, status message '${response.statusMessage}', took ${Date.now() - start} ms`);
}
switch (response.statusCode) {
case 200: // OK
case 301: // redirect - Moved - treat package as present
case 302: // redirect - Found - treat package as present
ok = true;
break;
}
response.destroy();
onRequestCompleted(ok);
}).on("error", (err: Error) => {
if (this.log.isEnabled()) {
this.log.writeLine(`${requestKind} #${requestId} query to npm registry failed with error ${err.message}, stack ${err.stack}`);
}
onRequestCompleted(/*success*/ false);
});
}
break;
case NpmInstallRequest: {
const command = `${this.npmPath} install ${args.join(" ")} --save-dev`;
const start = Date.now();
this.exec(command, { cwd }, (err, stdout, stderr) => {
if (this.log.isEnabled()) {
this.log.writeLine(`${requestKind} #${requestId} took: ${Date.now() - start} ms${sys.newLine}stdout: ${stdout}${sys.newLine}stderr: ${stderr}`);
}
// treat any output on stdout as success
onRequestCompleted(!!stdout);
});
}
break;
default:
Debug.assert(false, `Unknown request kind ${requestKind}`);
}
this.exec(command, { cwd }, (err, stdout, stderr) => {
if (this.log.isEnabled()) {
this.log.writeLine(`${requestKind} #${requestId} stdout: ${stdout}`);
this.log.writeLine(`${requestKind} #${requestId} stderr: ${stderr}`);
}
onRequestCompleted(err, stdout, stderr);
});
}
}
+13 -16
View File
@@ -65,11 +65,11 @@ namespace ts.server.typingsInstaller {
export type RequestKind = typeof NpmViewRequest | typeof NpmInstallRequest;
export type RequestCompletedAction = (err: Error, stdout: string, stderr: string) => void;
export type RequestCompletedAction = (success: boolean) => void;
type PendingRequest = {
requestKind: RequestKind;
requestId: number;
command: string;
args: string[];
cwd: string;
onRequestCompleted: RequestCompletedAction
};
@@ -88,7 +88,6 @@ namespace ts.server.typingsInstaller {
constructor(
readonly globalCachePath: string,
readonly npmPath: string,
readonly safeListPath: Path,
readonly throttleLimit: number,
protected readonly log = nullLog) {
@@ -331,13 +330,12 @@ namespace ts.server.typingsInstaller {
let execInstallCmdCount = 0;
const filteredTypings: string[] = [];
for (const typing of typingsToInstall) {
execNpmViewTyping(this, typing);
filterExistingTypings(this, typing);
}
function execNpmViewTyping(self: TypingsInstaller, typing: string) {
const command = `${self.npmPath} view @types/${typing} --silent name`;
self.execAsync(NpmViewRequest, requestId, command, cachePath, (err, stdout, stderr) => {
if (stdout) {
function filterExistingTypings(self: TypingsInstaller, typing: string) {
self.execAsync(NpmViewRequest, requestId, [typing], cachePath, ok => {
if (ok) {
filteredTypings.push(typing);
}
execInstallCmdCount++;
@@ -353,9 +351,8 @@ namespace ts.server.typingsInstaller {
return;
}
const scopedTypings = filteredTypings.map(t => "@types/" + t);
const command = `${self.npmPath} install ${scopedTypings.join(" ")} --save-dev`;
self.execAsync(NpmInstallRequest, requestId, command, cachePath, (err, stdout, stderr) => {
postInstallAction(stdout ? scopedTypings : []);
self.execAsync(NpmInstallRequest, requestId, scopedTypings, cachePath, ok => {
postInstallAction(ok ? scopedTypings : []);
});
}
}
@@ -403,8 +400,8 @@ namespace ts.server.typingsInstaller {
};
}
private execAsync(requestKind: RequestKind, requestId: number, command: string, cwd: string, onRequestCompleted: RequestCompletedAction): void {
this.pendingRunRequests.unshift({ requestKind, requestId, command, cwd, onRequestCompleted });
private execAsync(requestKind: RequestKind, requestId: number, args: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void {
this.pendingRunRequests.unshift({ requestKind, requestId, args, cwd, onRequestCompleted });
this.executeWithThrottling();
}
@@ -412,15 +409,15 @@ namespace ts.server.typingsInstaller {
while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) {
this.inFlightRequestCount++;
const request = this.pendingRunRequests.pop();
this.runCommand(request.requestKind, request.requestId, request.command, request.cwd, (err, stdout, stderr) => {
this.executeRequest(request.requestKind, request.requestId, request.args, request.cwd, ok => {
this.inFlightRequestCount--;
request.onRequestCompleted(err, stdout, stderr);
request.onRequestCompleted(ok);
this.executeWithThrottling();
});
}
}
protected abstract runCommand(requestKind: RequestKind, requestId: number, command: string, cwd: string, onRequestCompleted: RequestCompletedAction): void;
protected abstract executeRequest(requestKind: RequestKind, requestId: number, args: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void;
protected abstract sendResponse(response: SetTypings | InvalidateCachedTypings): void;
}
}
+2 -5
View File
@@ -6,9 +6,6 @@ namespace ts.NavigateTo {
const patternMatcher = createPatternMatcher(searchValue);
let rawItems: RawNavigateToItem[] = [];
// This means "compare in a case insensitive manner."
const baseSensitivity: Intl.CollatorOptions = { sensitivity: "base" };
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
for (const sourceFile of sourceFiles) {
cancellationToken.throwIfCancellationRequested();
@@ -187,8 +184,8 @@ namespace ts.NavigateTo {
// We first sort case insensitively. So "Aaa" will come before "bar".
// Then we sort case sensitively, so "aaa" will come before "Aaa".
return i1.matchKind - i2.matchKind ||
i1.name.localeCompare(i2.name, undefined, baseSensitivity) ||
i1.name.localeCompare(i2.name);
ts.compareStringsCaseInsensitive(i1.name, i2.name) ||
ts.compareStrings(i1.name, i2.name);
}
function createNavigateToItem(rawItem: RawNavigateToItem): NavigateToItem {
+2 -4
View File
@@ -330,10 +330,8 @@ namespace ts.NavigationBar {
}
}
// More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times.
const collator: { compare(a: string, b: string): number } = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined;
// Intl is missing in Safari, and node 0.10 treats "a" as greater than "B".
const localeCompareIsCorrect = collator && collator.compare("a", "B") < 0;
const localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0;
const localeCompareFix: (a: string, b: string) => number = localeCompareIsCorrect ? collator.compare : function(a, b) {
// This isn't perfect, but it passes all of our tests.
for (let i = 0; i < Math.min(a.length, b.length); i++) {
@@ -344,7 +342,7 @@ namespace ts.NavigationBar {
if (chA === "'" && chB === "\"") {
return -1;
}
const cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase());
const cmp = ts.compareStrings(chA.toLocaleLowerCase(), chB.toLocaleLowerCase());
if (cmp !== 0) {
return cmp;
}
+4 -3
View File
@@ -25,13 +25,14 @@
"../compiler/visitor.ts",
"../compiler/transformers/ts.ts",
"../compiler/transformers/jsx.ts",
"../compiler/transformers/es7.ts",
"../compiler/transformers/es6.ts",
"../compiler/transformers/es2017.ts",
"../compiler/transformers/es2016.ts",
"../compiler/transformers/es2015.ts",
"../compiler/transformers/generators.ts",
"../compiler/transformers/destructuring.ts",
"../compiler/transformers/module/module.ts",
"../compiler/transformers/module/system.ts",
"../compiler/transformers/module/es6.ts",
"../compiler/transformers/module/es2015.ts",
"../compiler/transformer.ts",
"../compiler/comments.ts",
"../compiler/sourcemap.ts",
+16 -16
View File
@@ -403,11 +403,11 @@ namespace ts {
export interface EditorSettings {
baseIndentSize?: number;
indentSize: number;
tabSize: number;
newLineCharacter: string;
convertTabsToSpaces: boolean;
indentStyle: IndentStyle;
indentSize?: number;
tabSize?: number;
newLineCharacter?: string;
convertTabsToSpaces?: boolean;
indentStyle?: IndentStyle;
}
/* @deprecated - consider using FormatCodeSettings instead */
@@ -428,19 +428,19 @@ namespace ts {
}
export interface FormatCodeSettings extends EditorSettings {
insertSpaceAfterCommaDelimiter: boolean;
insertSpaceAfterSemicolonInForStatements: boolean;
insertSpaceBeforeAndAfterBinaryOperators: boolean;
insertSpaceAfterKeywordsInControlFlowStatements: boolean;
insertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean;
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean;
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean;
insertSpaceAfterCommaDelimiter?: boolean;
insertSpaceAfterSemicolonInForStatements?: boolean;
insertSpaceBeforeAndAfterBinaryOperators?: boolean;
insertSpaceAfterKeywordsInControlFlowStatements?: boolean;
insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean;
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean;
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean;
insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean;
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean;
insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: boolean;
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean;
insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean;
insertSpaceAfterTypeAssertion?: boolean;
placeOpenBraceOnNewLineForFunctions: boolean;
placeOpenBraceOnNewLineForControlBlocks: boolean;
placeOpenBraceOnNewLineForFunctions?: boolean;
placeOpenBraceOnNewLineForControlBlocks?: boolean;
}
export interface DefinitionInfo {
+1 -1
View File
@@ -1339,7 +1339,7 @@ namespace ts {
const options: TranspileOptions = {
fileName: "config.js",
compilerOptions: {
target: ScriptTarget.ES6,
target: ScriptTarget.ES2015,
removeComments: true
},
reportDiagnostics: true
@@ -58,7 +58,7 @@ export function delint(sourceFile: ts.SourceFile) {
const fileNames: string[] = process.argv.slice(2);
fileNames.forEach(fileName => {
// Parse a file
let sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES6, /*setParentNodes */ true);
let sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES2015, /*setParentNodes */ true);
// delint it
delint(sourceFile);
@@ -113,7 +113,7 @@ exports.delint = delint;
var fileNames = process.argv.slice(2);
fileNames.forEach(function (fileName) {
// Parse a file
var sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES6, /*setParentNodes */ true);
var sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES2015, /*setParentNodes */ true);
// delint it
delint(sourceFile);
});
@@ -0,0 +1,10 @@
tests/cases/compiler/alwaysStrict.ts(3,9): error TS1100: Invalid use of 'arguments' in strict mode.
==== tests/cases/compiler/alwaysStrict.ts (1 errors) ====
function f() {
var arguments = [];
~~~~~~~~~
!!! error TS1100: Invalid use of 'arguments' in strict mode.
}
+11
View File
@@ -0,0 +1,11 @@
//// [alwaysStrict.ts]
function f() {
var arguments = [];
}
//// [alwaysStrict.js]
"use strict";
function f() {
var arguments = [];
}
@@ -0,0 +1,11 @@
//// [alwaysStrictAlreadyUseStrict.ts]
"use strict"
function f() {
var a = [];
}
//// [alwaysStrictAlreadyUseStrict.js]
"use strict";
function f() {
var a = [];
}
@@ -0,0 +1,8 @@
=== tests/cases/compiler/alwaysStrictAlreadyUseStrict.ts ===
"use strict"
function f() {
>f : Symbol(f, Decl(alwaysStrictAlreadyUseStrict.ts, 0, 12))
var a = [];
>a : Symbol(a, Decl(alwaysStrictAlreadyUseStrict.ts, 2, 7))
}
@@ -0,0 +1,11 @@
=== tests/cases/compiler/alwaysStrictAlreadyUseStrict.ts ===
"use strict"
>"use strict" : "use strict"
function f() {
>f : () => void
var a = [];
>a : any[]
>[] : undefined[]
}
@@ -0,0 +1,10 @@
tests/cases/compiler/alwaysStrictES6.ts(3,9): error TS1100: Invalid use of 'arguments' in strict mode.
==== tests/cases/compiler/alwaysStrictES6.ts (1 errors) ====
function f() {
var arguments = [];
~~~~~~~~~
!!! error TS1100: Invalid use of 'arguments' in strict mode.
}
@@ -0,0 +1,11 @@
//// [alwaysStrictES6.ts]
function f() {
var arguments = [];
}
//// [alwaysStrictES6.js]
"use strict";
function f() {
var arguments = [];
}
@@ -0,0 +1,12 @@
tests/cases/compiler/alwaysStrictModule.ts(4,13): error TS1100: Invalid use of 'arguments' in strict mode.
==== tests/cases/compiler/alwaysStrictModule.ts (1 errors) ====
module M {
export function f() {
var arguments = [];
~~~~~~~~~
!!! error TS1100: Invalid use of 'arguments' in strict mode.
}
}
@@ -0,0 +1,17 @@
//// [alwaysStrictModule.ts]
module M {
export function f() {
var arguments = [];
}
}
//// [alwaysStrictModule.js]
"use strict";
var M;
(function (M) {
function f() {
var arguments = [];
}
M.f = f;
})(M || (M = {}));
@@ -0,0 +1,22 @@
tests/cases/compiler/a.ts(4,13): error TS1100: Invalid use of 'arguments' in strict mode.
tests/cases/compiler/b.ts(3,13): error TS1100: Invalid use of 'arguments' in strict mode.
==== tests/cases/compiler/a.ts (1 errors) ====
module M {
export function f() {
var arguments = [];
~~~~~~~~~
!!! error TS1100: Invalid use of 'arguments' in strict mode.
}
}
==== tests/cases/compiler/b.ts (1 errors) ====
module M {
export function f2() {
var arguments = [];
~~~~~~~~~
!!! error TS1100: Invalid use of 'arguments' in strict mode.
}
}
@@ -0,0 +1,34 @@
//// [tests/cases/compiler/alwaysStrictModule2.ts] ////
//// [a.ts]
module M {
export function f() {
var arguments = [];
}
}
//// [b.ts]
module M {
export function f2() {
var arguments = [];
}
}
//// [out.js]
"use strict";
var M;
(function (M) {
function f() {
var arguments = [];
}
M.f = f;
})(M || (M = {}));
"use strict";
var M;
(function (M) {
function f2() {
var arguments = [];
}
M.f2 = f2;
})(M || (M = {}));
@@ -0,0 +1,14 @@
error TS5053: Option 'noImplicitUseStrict' cannot be specified with option 'alwaysStrict'.
tests/cases/compiler/alwaysStrictNoImplicitUseStrict.ts(4,13): error TS1100: Invalid use of 'arguments' in strict mode.
!!! error TS5053: Option 'noImplicitUseStrict' cannot be specified with option 'alwaysStrict'.
==== tests/cases/compiler/alwaysStrictNoImplicitUseStrict.ts (1 errors) ====
module M {
export function f() {
var arguments = [];
~~~~~~~~~
!!! error TS1100: Invalid use of 'arguments' in strict mode.
}
}
@@ -0,0 +1,17 @@
//// [alwaysStrictNoImplicitUseStrict.ts]
module M {
export function f() {
var arguments = [];
}
}
//// [alwaysStrictNoImplicitUseStrict.js]
"use strict";
var M;
(function (M) {
function f() {
var arguments = [];
}
M.f = f;
})(M || (M = {}));
@@ -0,0 +1,6 @@
//// [arrowFunctionWithParameterNameAsync_es2017.ts]
const x = async => async;
//// [arrowFunctionWithParameterNameAsync_es2017.js]
var x = function (async) { return async; };
@@ -0,0 +1,7 @@
=== tests/cases/conformance/async/es2017/asyncArrowFunction/arrowFunctionWithParameterNameAsync_es2017.ts ===
const x = async => async;
>x : Symbol(x, Decl(arrowFunctionWithParameterNameAsync_es2017.ts, 1, 5))
>async : Symbol(async, Decl(arrowFunctionWithParameterNameAsync_es2017.ts, 1, 9))
>async : Symbol(async, Decl(arrowFunctionWithParameterNameAsync_es2017.ts, 1, 9))
@@ -0,0 +1,8 @@
=== tests/cases/conformance/async/es2017/asyncArrowFunction/arrowFunctionWithParameterNameAsync_es2017.ts ===
const x = async => async;
>x : (async: any) => any
>async => async : (async: any) => any
>async : any
>async : any
@@ -0,0 +1,12 @@
tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts(4,11): error TS2304: Cannot find name 'await'.
==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts (1 errors) ====
var foo = async (): Promise<void> => {
// Legal to use 'await' in a type context.
var v: await;
~~~~~
!!! error TS2304: Cannot find name 'await'.
}
@@ -0,0 +1,13 @@
//// [asyncArrowFunction10_es2017.ts]
var foo = async (): Promise<void> => {
// Legal to use 'await' in a type context.
var v: await;
}
//// [asyncArrowFunction10_es2017.js]
var foo = async () => {
// Legal to use 'await' in a type context.
var v;
};
@@ -0,0 +1,8 @@
//// [asyncArrowFunction1_es2017.ts]
var foo = async (): Promise<void> => {
};
//// [asyncArrowFunction1_es2017.js]
var foo = async () => {
};
@@ -0,0 +1,7 @@
=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction1_es2017.ts ===
var foo = async (): Promise<void> => {
>foo : Symbol(foo, Decl(asyncArrowFunction1_es2017.ts, 1, 3))
>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --))
};
@@ -0,0 +1,8 @@
=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction1_es2017.ts ===
var foo = async (): Promise<void> => {
>foo : () => Promise<void>
>async (): Promise<void> => {} : () => Promise<void>
>Promise : Promise<T>
};
@@ -0,0 +1,7 @@
//// [asyncArrowFunction2_es2017.ts]
var f = (await) => {
}
//// [asyncArrowFunction2_es2017.js]
var f = (await) => {
};
@@ -0,0 +1,5 @@
=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction2_es2017.ts ===
var f = (await) => {
>f : Symbol(f, Decl(asyncArrowFunction2_es2017.ts, 0, 3))
>await : Symbol(await, Decl(asyncArrowFunction2_es2017.ts, 0, 9))
}
@@ -0,0 +1,6 @@
=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction2_es2017.ts ===
var f = (await) => {
>f : (await: any) => void
>(await) => {} : (await: any) => void
>await : any
}
@@ -0,0 +1,8 @@
tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction3_es2017.ts(1,20): error TS2372: Parameter 'await' cannot be referenced in its initializer.
==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction3_es2017.ts (1 errors) ====
function f(await = await) {
~~~~~
!!! error TS2372: Parameter 'await' cannot be referenced in its initializer.
}
@@ -0,0 +1,7 @@
//// [asyncArrowFunction3_es2017.ts]
function f(await = await) {
}
//// [asyncArrowFunction3_es2017.js]
function f(await = await) {
}
@@ -0,0 +1,7 @@
//// [asyncArrowFunction4_es2017.ts]
var await = () => {
}
//// [asyncArrowFunction4_es2017.js]
var await = () => {
};
@@ -0,0 +1,4 @@
=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction4_es2017.ts ===
var await = () => {
>await : Symbol(await, Decl(asyncArrowFunction4_es2017.ts, 0, 3))
}

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